Strict mode in JavaScript restricts access to variables that have not been previously declared. This means that the variable isTrue
must be declared before it can be accessed. If you remove the var
declaration in front of it and it is not declared elsewhere, an error will occur.
The MDN page on strict mode explains:
In strict mode, creating accidental global variables is prevented. In regular JavaScript, mistyping a variable in an assignment would create a new global property and still "work," but may fail in the future. Assignments that would accidentally create global variables throw errors in strict mode:
Your question about undefined
is more complex due to variable hoisting. In your code with the var
statement, it is equivalent to this:
var isTrue;
try
{
isDefined(isTrue);
}
catch (ex)
{
isTrue = false;
}
isTrue = true;
So, when you call isDefined(isTrue)
, the value of isTrue
is undefined
because it has been declared but not initialized yet. Without the var
statement, referencing isTrue
in strict mode will result in an error since it has not been declared at that point.
If you only want to check if a variable has a value, you can do:
if (typeof isTrue != "undefined") {
// code here for defined variable
}
Or, if you want to ensure it has a value even if it hasn't been initialized, you can use:
if (typeof isTrue == "undefined") {
var isTrue = false;
}