What is difference between declaring variable using var and without var?
a=2;
b=2;
if(a==b)//returning false
if(a===b)//returning false
var a=2;
var b=2;
if(a==b)//returning true
if(a===b)//returning true
Why?
What is difference between declaring variable using var and without var?
a=2;
b=2;
if(a==b)//returning false
if(a===b)//returning false
var a=2;
var b=2;
if(a==b)//returning true
if(a===b)//returning true
Why?
Without var
will declare the variable globally. Using var
will declare the variable locally in the current scope.
var defines variable globally, Means that variable defined with var can be accessible form any script below it. And without var it cant
We use var
for all types because since JavaScript has dynamic typing the type can be inferred automatically during run-time.
Now, for the difference between using the var or not, if you're in a function then var will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope at which point it will create it.