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?
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 }
var awill create a local variable. Another will create and / or set a global variable.
var a
In most cases, you are better off creating local variables unless you need to create a global variable.
, - .
var , .
var
, , .
, , ( , , ).
. , , .
, 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.