4

what is the difference between the way a variable can be declared?

a = 5;

and

var a = 5;

Is there any relation with scoping also?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
kamal
  • 996
  • 15
  • 25

4 Answers4

2

var a will create local variable. The other will create and/or set a global variable.

Most of the time, you are better off creating local variables, unless you absolutely need to create a global variable.

manojlds
  • 290,304
  • 63
  • 469
  • 417
1

a = 5 will declare a global variable from any scope. var a = 5 will declare a variable within the declared scope.

 a = 5;    //global variable
 var b = 6; // global variable
 function foo(){
  var c = 7; //local variable
  d = 9; //global variable
  }
Himanshu Tanwar
  • 906
  • 6
  • 18
1

One declares a variable, the other one doesn't.

The var keyword is for declaring variables, and the variable is created in the current scope.

If you assign a value to a variable that doesn't exist yet, the variable is implicitly created in the global scope.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1
a = 5;

This will set a variable, if the variable has not already been declared then it will be created in the global scope (which you probably don't want).

var a = 5;

This will create and set a variable. The variable will be created as a local variable in the function scope if inside a function, otherwise will create it globally.

Also worth noting that the statement var a = 5 will be hoisted to the top of your function. I.e.

function() {
    doSomestuff();
    a = 4;
    var a = 5;
    doOtherStuff();
}

actually becomes

function() {
    var a = 5;
    doSomestuff();
    a = 4;
    doOtherStuff();
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var for more info.

Also worth noting that if you use strict mode you cannot declare a variable with just a = 5. You must use the var keyword.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

This is worth doing because turns your undetectable mistakes into obvious errors.

Jonny
  • 796
  • 2
  • 10
  • 23