Difference between declaring variable

What is the difference between how a variable can be declared?

a = 5;

and

var a = 5;

Is there any relation to the definition of scope?

+4
source share
4 answers

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

 a = 5;    //global variable
 var b = 6; // global variable
 function foo(){
  var c = 7; //local variable
  d = 9; //global variable
  }
+1
source

var awill create a local variable. Another will create and / or set a global variable.

In most cases, you are better off creating local variables unless you need to create a global variable.

+2
source

, - .

var , .

, , .

+1
a = 5;

, , ( , , ).

var a = 5;

. , , .

, var a = 5 . .

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

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

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

, , a = 5. var.

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

It is worth it to turn your undetectable errors into obvious errors.

+1
source

All Articles