Search This Blog

2024/03/24

Javascript Interview Question:Operation on undefined variable

consider code snippet below

Code:
x++;
console.log(x);
var x = 21;

Output:
NaN

Explanation:

Here we are doing mathematical operation on undefined hence NaN.

Code Snippet 2:

Code :
var x = 23;
(function () {
var x = 43;
(function random() {
x++;
console.log(x);
var x = 21;
})();
})();

Output:
NaN

Explanation:
Here two Immediately Invocable functions are nexted inside one another.
In top IIFE x is defined again using var.
In IIFE nexted inside again x is defined using var.
So here due to Hoisting behaviour code line above it get value of x as undefined.
on the first line we are doing mathematical operation on undefined so x become NaN.
the code line after that

console.log(x)

prints

NaN

No comments:

Post a Comment