JavaScript Function Expression
Functions are essential JavaScript building pieces that let us organise statements for reuse, as we’ve seen. We have discussed how functions can return values, how to define them, and how to provide data to them using arguments and parameters.
JavaScript enables you to define a function as part of a larger expression, in addition to defining functions with a function declaration statement (such as function myFunction() {… }). We call this a function expression.
The main idea here is that JavaScript functions are values as well as syntax. A function can be thought of as a value in the same way that a text (“hello”) or a number (42) is a value. A piece of code that can be evaluated to get a value is called an expression. Consequently, an expression that evaluates to a function value is called a function expression.
Anonymous Functions
Assigning an anonymous function to a variable is the most popular method for creating a function expression. A function without a name immediately following the function keyword is known as an anonymous function. Here’s a common syntax pattern for a Function Expression:
let functionName = function(parameter1, parameter2) {
// Function body – statements to be executed
// Can use parameters
// Can return a value
return someValue;
};
The function expression in this case is function(parameter1, parameter2) {… }. The function value it generates is subsequently allocated to the variable functionName. Similar to calling a function declared with a statement, you then use the variable name followed by brackets to call the function.
// Function Expression assigned to a variable
const multiply = function(x, y) { // ‘multiply’ is the variable, the function itself is anonymous
return x * y;
};
let product = multiply(6, 7); // Call the function using the variable name
console.log(product);
// Output: 42
The function name that appears immediately after the function in the expression is optional. An anonymous function is obtained when it is omitted. This is helpful for recursive calls where the function must refer to itself since, if a name is provided (let fact = function factorial(n) {… }), it is usually only accessible within the code’s own scope.
Hoisting is a crucial distinction between function declarations and function expressions. The JavaScript engine processes function declarations before the code begins running, making them accessible across their scope, including lines of code that come before the declaration. However, function expressions are only produced and made available when the line of code that contains them is run. A function expression cannot be called until it has been assigned to something you may reference and appears in the code.
// Example of hoisting difference
// This works (Function Declaration is hoisted)
greet(“Alice”);
// Output: Hello, Alice!
function greet(name) {
console.log(“Hello, ” + name + “!”);
}
// This will cause an error (Function Expression is not hoisted)
// sayHello(“Bob”); // TypeError: sayHello is not a function
const sayHello = function(name) {
console.log(“Hello, ” + name + “!”);
};
sayHello(“Bob”); // This works now
Function expressions are very helpful because they let you treat functions as data, which makes it possible to create strong patterns:
Assigning to variables or properties: As previously mentioned, you can create methods and put functions in variables or as properties of objects.
Passing as arguments: Functions can be passed to other functions as arguments. They are frequently referred to as callback functions. An example of passing an anonymous function expression as an argument to the sort() method of an array.
Immediately Invoked Function Expressions (IIFEs)
A function that is defined and run instantly is known as an Immediately Invoked Function Expression (IIFE). It’s a method of describing a function that makes it execute immediately.
Usually, IIFEs are self-executing and anonymous. In order to invoke a function expression, the syntax typically entails wrapping it in parentheses () and then immediately following it with another set of parentheses (). To guarantee that the JavaScript engine interprets the function keyword as a component of an expression rather than a function declaration statement, the first brackets are frequently required.
The creation of a private scope is a crucial use for IIFEs. Declared variables inside an IIFE are specific to that function and aid in keeping the global namespace clean. When defining private variables and functions or initialising code, IIFEs can be helpful. Within the second set of parenthesis, you can send parameters to an IIFE, and they can return values as well.
Here’s a basic example:
(function() { // The function expression
let message = “Hello from IIFE!”;
console.log(message); // This is inside the IIFE’s scope
})(); // Immediately invoked
// console.log(message); // This would cause an error outside
For a shorter IIFE, arrow functions can also be utilised.
Function expressions can be written more succinctly using arrow functions (=> syntax), especially for simple functions. They behave somewhat differently when it comes to this bond, which is a more complex subject.
In conclusion, Function Expressions enable powerful programming patterns by giving you the freedom to build functions dynamically within your code, treat them as values, and utilise them in a variety of settings, including assignments, arguments, and instant execution.