In JavaScript, there are two main ways to define a function: function declaration and function expression. While both methods allow you to create a function in JavaScript, there are some key differences between them.
Function Declaration: A function declaration is a statement that defines a named function. It starts with the function keyword, followed by the function name, a set of parentheses, and a block of code. Here is an example:
function add(a, b) {
return a + b;
}
In this example, the function add is declared with two parameters a and b. The function body simply adds these two parameters and returns the result.
One of the main differences between function declarations and function expressions is that function declarations are hoisted to the top of their scope. This means that you can call a function before it is declared in your code. Here is an example:
console.log(add(2, 3)); // Outputs 5
function add(a, b) {
return a + b;
}
In this example, the add function is called before it is declared in the code. This works because the function declaration is hoisted to the top of the scope.
Function Expression: A function expression is similar to a function declaration, but it is defined as part of an expression, such as a variable assignment. Here is an example:
var add = function(a, b) {
return a + b;
};
In this example, the add function is assigned to a variable. This variable can then be used to call the function.
One key difference between function declarations and function expressions is that function expressions are not hoisted to the top of their scope. This means that you cannot call a function expression before it is defined in your code. Here is an example:
console.log(add(2, 3)); // Throws an error
var add = function(a, b) {
return a + b;
};
In this example, the add function is called before it is defined in the code. This does not work because the function expression is not hoisted to the top of the scope.
In summary, function declarations and function expressions are two ways to define functions in JavaScript. Function declarations are statements that define named functions and are hoisted to the top of their scope. Function expressions are defined as part of an expression and are not hoisted to the top of their scope.