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,
isTruemust be declared before you can access it. Thus, if you remove thevarin front of it and it isn’t declared anywhere else, that will be an error.Quoting from the MDN page on strict mode:
The part of your question about
undefinedis 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 thevarstatement is equivalent to this:Thus, when you call
isDefined(isTrue), the value ofisTrueisundefined. It’s been declared, but not initialized, therefore it’s value isundefined. When you don’t have thevarstatement, any reference toisTruein 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:
Or, if you just want to make sure it has a value if it hasn’t already been initialized, you can do this: