This question already has an answer here:
Is "var" optional?
myObj = 1;
same as ?
var myObj = 1;
I found they both work from my test, I assume var
is optional. Is that right?
This question already has an answer here:
Is "var" optional?
myObj = 1;
same as ?
var myObj = 1;
I found they both work from my test, I assume var
is optional. Is that right?
No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.
Nope, they are not equivalent.
With
myObj = 1;
you are using a global variable.The latter declaration create a variable local to the scope you are using.
Try the following code to understand the differences:
The second function alters the value of the global variable "external", but the first function doesn't.