Function is a procedure to perform certain tasks by taking input and return output using the input. In this article, we will explore the definition of JavaScript function declaration and function expression to understand the difference between them.
Definition
Function declaration
function
keyword + specify name
function sum(a, b) {
return a + b;
}
console.log(sum(1, 2)) // 3
hoisted - can be called before it is defined
can be used after the entire script has been parsed
Function expression
- anonymous - function does not have a name
const sum = function(a, b) {
return a + b;
};
console.log(sum(1, 2)) // 3
- a name can be provided to refer itself
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3)); // 6
can not use before its definition
can be used as an argument to another function
Function hoisting
JavaScript Hoisting is the process which the interpreter moves the declaration of functions, variables, classes or imports to the top of the scope before the execution of the code.
console.log(sum(1, 2)) // 3
function sum(a, b) {
return a + b;
}
// with function expression,
// it gives error if it is used before its definition
When to use function declaration and and function expression?
function declaration - to create a function on the global scope
function expression - to create a function which accessibility is limited, useful for anonymous operation(Immediately Invoked Function Expressions, Callback function)