We all know about JavaScript functions, how we can define and call a function.
- function add(a, b)
- {
- return a + b;
- }
- add(5, 6);
What is function hoisting?
- function add(a, b) {
- return a + b;
- }
- add(5, 6);
-
- function add(a, b) {
- return a - b;
- }
- 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:
- var add = function(a, b) {
- return a + b;
- };
- add(5, 6);
- var add = function(a, b) {
- return a - b;
- };
- 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.