If you might have been working with some language like C or Java or might be some other object oriented language, you surely might be knowing that every variable/function has a scope of execution.
Take a look on the below piece of code:
if (true)
{
var blockLevel = "I am in first if block";
}
if (true)
{
console.log(blockLevel); //variable 'blockLevel' is visible here.
}
}
But unfortunately this is not correct.
To your surprise the second if block will successfully print "I am in first if block" on console!!!!
This is because unlike many other languages javascript does not have any block level scope.
It is therefore suggested to always declare variables at the top of the function and not inside blocks.
Even when you are declare a var statement inside a for or in for/in loop, The variable is not only visible in that loop, rather it will be visible in the whole function indeed in which the loop exists.
var count = 5;
for(var count = 0; count<10; i++)
{
}
if(true)
{
console.log(count)//what should be the value of count?
//Surprisingly the value will be 10 ,not 5
}
}
Note - Javascript does not have block level scope but have function level scope. Therefore variable declared in one function is not visible in another function.