I have the following code:
"use strict";
function isDefined(variable)
{
return (typeof (window[variable]) === "undefined") ? false : true;
}
try
{
isDefined(isTrue);
}
catch (ex)
{
var isTrue = false;
}
isTrue = true;
Can someone please explain to me why when I remove the keyword 'var' I get an exception thrown but when it is there it treats it like undefined?
When running in strict mode, you aren't allow to access variables that aren't previously declared. So, isTrue
must be declared before you can access it. Thus, if you remove the var
in front of it and it isn't declared anywhere else, that will be an error.
Quoting from the MDN page on strict mode:
First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw in strict mode:
The part of your question about undefined
is a little more complicated. Because of variable hoisting where a variable declaration is hoisted by the compiler to the top of the scope it's declared in, your code with the var
statement is equivalent to this:
var isTrue;
try
{
isDefined(isTrue);
}
catch (ex)
{
isTrue = false;
}
isTrue = true;
Thus, when you call isDefined(isTrue)
, the value of isTrue
is undefined
. It's been declared, but not initialized, therefore it's value is undefined
. When you don't have the var
statement, any reference to isTrue
in strict mode is an error since it hasn't been declared yet.
If you just want to know if a variable has a value yet, you can simply do this:
if (typeof isTrue != "undefined") {
// whatever code here when it is defined
}
Or, if you just want to make sure it has a value if it hasn't already been initialized, you can do this:
if (typeof isTrue == "undefined") {
var isTrue = false;
}