DEV Community

Sagar Gnawali
Sagar Gnawali

Posted on

Day 5 -> 40 days of code.

If we defined any variable and don't assign any value to it and if console.log() it then it will show undefined this happened with only var and let keyword.

In JavaScript hoisting is the default behavior of moving all the declaration at the top of the scope before code execution.
Hoisting is only happen with var.
To avoid hoisting always define a variable at the top of the program.

Let's see what does it means in coding part.
eg.
console.log(x);//undefined
var x;

eg.
var a=10;
const print =()=>
{
console.log(a);//undefined
var a;
}
print();

Here we see that a prints undefined because of hoisting.
If we remove the var a from the print function then it will print a as 10.

Top comments (0)