Advanced Features of Functions
Let's explore more advanced ways to use functions.
Callback Function
A callback function is a function that is passed as an argument to another function.
Calling a callback function passed as an argument
function study(callback) {
console.log('Studying...');
callback(); // Call the callback function
}
study(() => {
console.log('Finished studying!');
});
Recursive Function
A recursive function is a function that calls itself.
Implementing factorial with a recursive function
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Outputs 120
IIFE (Immediately Invoked Function Expression)
IIFE is a pattern where a function is defined and immediately invoked.
Example:
Using IIFE
(function () {
console.log('This function runs immediately!');
})();
Built-in Functions and Usage Examples
JavaScript provides many useful built-in functions. For example, it supports functions to sort arrays or slice strings.
Example:
Using the built-in sort function
let arr = [3, 1, 4, 1, 5, 9];
arr.sort();
console.log(arr); // Outputs [1, 1, 3, 4, 5, 9]
let str = 'Hello, world!';
let slicedStr = str.slice(0, 5);
console.log(slicedStr); // Outputs "Hello"
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.