Home Courses Function Expression Hoisting & Rest Operator

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();

  1. You have to use the variable name (fruitExpression) to call it
  2. 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");
}

  1. This works because of hoisting


Function expression:


fruitExpression();

let fruitExpression = function(){
console.log("banana");
}

  1. This will not work
  2. Error: cannot access before initialization


Using var:


console.log(fruitExpression);

var fruitExpression = function(){
console.log("banana");
}

  1. Output will be undefined
  2. Only variable is hoisted, not the function


Key Difference in Hoisting

  1. Function declaration → hoisting works
  2. 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);

  1. Output: 2


Rest Operator


let recursionX = function(...val){
console.log(val);
}

recursionX(10,20,30,40);

  1. Output: [10,20,30,40]


Types of Function Expression

  1. Named function expression:

let test = function myFunc(){
console.log("hello");
}

  1. Anonymous function expression:

let test = function(){
console.log("hello");
}


Difference Between Function Declaration and Function Expression

  1. Function declaration:
  2. Fully hoisted
  3. Can call before declaration
  4. Cannot store in variable
  5. Not anonymous
  6. Rarely used in callbacks
  7. Function expression:
  8. Not hoisted
  9. Cannot call before declaration
  10. Can store in variable
  11. Can be anonymous
  12. Commonly used in callbacks
  13. Preferred in modern JavaScript


Final Code


let recursionX = function recursion(...val) {
console.log(val);
}

recursionX(10,20,30,40);


Share this lesson: