Just starting out learning JS. I understand defining variables. Why leave one undeclared? Does it help when constructing if/then statements?
Asked
Active
Viewed 218 times
-2
-
1This might be a duplicate: http://stackoverflow.com/questions/15985875/effect-of-declared-and-undeclared-variables – dbarnes Aug 26 '13 at 02:45
2 Answers
3
Why leave one undeclared?
function foo() {
var i = 0; // local variable
j = 1; // global variable
}
foo();
i; // undefined
j; // 1
function bar() {
var k; // local variable
k = 2; // still local
}
bar();
k; // undefined
If foo
is in "use strict"
mode, it will cause a ReferenceError: j is not defined
unless another j
is defined higher up the scope chain, because there was no var
for the j
.

Paul S.
- 64,864
- 9
- 122
- 138
-
as far as i know you cant declare a global variable **inside** a function and "j=1;" (if its not a error) will be a local variable – Math chiller Aug 26 '13 at 02:54
-
@tryingToGetProgrammingStraight If you don't believe it, try the code I've posted here, followed by a check to see if there is a global `j` and report back :-) I believe that the `j;` outside of the _function_ as in my example is sufficient proof, though. – Paul S. Aug 26 '13 at 02:56
-
It is true that `j` will not necessarily become global if there is a `var j` higher in scope but not globally, though. – Paul S. Aug 26 '13 at 02:59
-
1
yep it can "help when constructing if/then statements?" the value of undefined is false. so:
if ( myVar )
means if its got a value true if not false
but its best to do:
var myVar;
which still is false not declaring may give a error in a older browser
im not sure happens if you already have a global "var i;" and then try using one in a loop, i think it will just make you lose the global "i" for the new one.

Math chiller
- 4,123
- 6
- 28
- 44
-
`the value of undefined is false`; _undefined_ is falsy, but `undefined !== false` – Paul S. Aug 26 '13 at 02:51
-
@PaulS. true (lol) but it will still work for a "if(undeclaredVariable)" – Math chiller Aug 26 '13 at 02:52