Hoisting
You can use (call) a function before it is defined!
const result = add(2, 1); console.log(result); function add(a, b) { return a + b; }
The observed phenomenon is due to hoisting.
Hoisting is a JavaScript mechanism where variables (declared with
var
keyword) and function declarations are moved to the top of their scope before code execution.
The caveat is when using function expressions; they are not hoisted!
const result = add(2, 1); console.log(result); const add = function (a, b) { return a + b; }
Here is a clever example that uses (mutual) recursion and hoisting:
function isEven(n) { return n == 0 ? true : isOdd(n - 1); } function isOdd(n) { return n == 0 ? false : isEven(n - 1); } const n = 3; // feel free to change this value! console.log(`isEven(${n}) -> ${isEven(n)}`); console.log(`isOdd(${n}) -> ${isOdd(n)}`);
Step-by-step execution
Here is a tricky example of hoisting: what does this snippet print?
var num = 1; print(); function print() { console.log(num); var num = 2; }
Explanation
The answer is undefined
because the num
variable inside the print
function is hoisted to the top of its scope (which is the top of the print
function).
The following snippet shows, roughly, how the hoisting works for the given example:
var num;
num = 1;
function print() {
var num;
console.log(num);
num = 2;
}
print();