JavaScript Function Hoisting

We all know about JavaScript functions, how we can define and call a function.

  1. function add(a, b)  
  2. {  
  3.     return a + b;  
  4. }  
  5. add(5, 6);  
What is function hoisting?
  1. function add(a, b) {  
  2.     return a + b;  
  3. }  
  4. add(5, 6);  
  5.   
  6. function add(a, b) {  
  7.     return a - b;  
  8. }  
  9. add(6, 5);  
Both the function calls will execute second implementation of the add function. Output will be -1 and 1.

The reason behind this is hoisting, JavaScript will replace the implementation of the first function with the second one. To solve this problem, we can use the function expressions. To declare the function expression, we need to write the code, given below:
  1. var add = function(a, b) {  
  2.     return a + b;  
  3. };  
  4. add(5, 6);  
  5. var add = function(a, b) {  
  6.     return a - b;  
  7. };  
  8. add(7, 6);  
Now, the result will be 11 and then 1. The reason behind this is, function is associated with the variable only. There is no existence for the function independently.

 

Ebook Download
View all
Learn
View all