0

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?

  • 1
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var – zerkms Jul 09 '16 at 06:38
  • 2
    see this link http://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – AKZ Jul 09 '16 at 06:39
  • is that true?https://jsfiddle.net/kzv5b0bd/ – Madhawa Priyashantha Jul 09 '16 at 06:42
  • http://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – shanthi Jul 09 '16 at 06:46
  • 1
    The answer to what you've asked is in the linked duplicate. Regarding the behaviour of the code you've shown, there must be more to it than what you've shown, because those first two if conditions will be `true`, not `false`. – nnnnnn Jul 09 '16 at 06:51

3 Answers3

3

Without var will declare the variable globally. Using var will declare the variable locally in the current scope.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
0

var defines variable globally, Means that variable defined with var can be accessible form any script below it. And without var it cant

Waleed Ahmed Haris
  • 1,229
  • 11
  • 17
0

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.

BernardoGO
  • 1,826
  • 1
  • 20
  • 35