Function Expression Hoisting & Rest Operator
When we assign a function to a variable and then use it, it is called a function expression.
Example
let fruitExpression = function fruit(){
console.log("apple");
}
fruitExpression();
- You have to use the variable name (
fruitExpression) to call it - Calling
fruit()will not work because it is assigned inside the variable
Function Expression with Parameter
let fruitExpression = function fruit(item){
console.log(item);
}
fruitExpression("apple");
Hoisting in Function Expression
Function declaration:
fruit();
function fruit(){
console.log("apple");
}
- This works because of hoisting
Function expression:
fruitExpression();
let fruitExpression = function(){
console.log("banana");
}
- This will not work
- Error: cannot access before initialization
Using var:
console.log(fruitExpression);
var fruitExpression = function(){
console.log("banana");
}
- Output will be
undefined - Only variable is hoisted, not the function
Key Difference in Hoisting
- Function declaration → hoisting works
- Function expression → hoisting does not work
Recursion Example
let recursionX = function recursion(val){
console.log(val);
if(val > 0){
recursion(val - 1);
}
}
recursionX(10);
Function Length
let test = function(a, b){
console.log(a, b);
}
console.log(test.length);
- Output:
2
Rest Operator
let recursionX = function(...val){
console.log(val);
}
recursionX(10,20,30,40);
- Output:
[10,20,30,40]
Types of Function Expression
- Named function expression:
let test = function myFunc(){
console.log("hello");
}
- Anonymous function expression:
let test = function(){
console.log("hello");
}
Difference Between Function Declaration and Function Expression
- Function declaration:
- Fully hoisted
- Can call before declaration
- Cannot store in variable
- Not anonymous
- Rarely used in callbacks
- Function expression:
- Not hoisted
- Cannot call before declaration
- Can store in variable
- Can be anonymous
- Commonly used in callbacks
- Preferred in modern JavaScript
Final Code
let recursionX = function recursion(...val) {
console.log(val);
}
recursionX(10,20,30,40);