JavaScript functions are an essential part of the JavaScript programming language. They are reusable blocks of code that perform specific tasks or calculations. Functions can take in parameters, perform operations, and return values. In this comprehensive guide, we will explore the various aspects of JavaScript functions, including function declarations, function expressions, arrow functions, anonymous functions, higher-order functions, and more.
Function Declarations:
A function declaration defines a named function using the “function” keyword. It consists of the function name, a list of parameters (optional), and the function body enclosed in curly braces.
function walk(road) {
console.log("Walking on the " + road + " road!");
}
walk("Chevy Chase Circle"); // Output: Walking on the Chevy Chase Circle road!
Function Expressions:
Function expressions define functions as values assigned to variables. They don’t require a function name (anonymous functions) or can have a name for better debugging (named function expressions).
//anonymous function assigned to variable walk
var walk = function(road) {
console.log("Walking around " + road + "!");
};
walk("Dupont Circle"); // Output: Walking around Dupont Circle!
Arrow Functions:
Arrow functions are a concise syntax introduced in ES6 for writing functions. They have a more compact syntax compared to regular functions. Unlike regular functions, arrow functions do not bind their own this
value. Instead, they lexically bind this
to the enclosing scope. This behavior is often desired when working with callbacks and event handlers.
var walk = road => {
console.log("Walking around " + road + "!");
};
walk("Grant Circle"); // Output: Walking around Grant Circle!
var road = {
name: "Logan Circle",
walk: function() {
setTimeout(() => {
console.log("Walking around " + this.name + "!");
}, 1000);
}
};
road.walk(); // Output: Walking around Logan Circle! (after 1 second)
road.walk();
road.name = "Scott Circle";
road.walk();
/* output:
Walking around Scott Circle!
Walking around Scott Circle!
*/
In the above, can you guess why it’s giving the output “Walking around Scott Circle! Walking around Scott Circle!” while the expected output was “Walking around Logan Circle! Walking around Scott Circle!”?