What are Asserts in Python and how to use them?
Hi Jasmine,
If you want to check whether a variable has been declared, regardless of its value, using the in
operator is the safest method. For example:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
However, using typeof
may not give the intended result in all cases because the variable might be declared but not initialized. The in
operator provides a more robust check:
"theFu" in window; // true
"theFoo" in window; // false
If you want to know whether the variable hasn’t been declared or has the value undefined
, use the typeof
operator, which is guaranteed to return a string:
if (typeof myVar !== 'undefined')
Direct comparisons against undefined
can be problematic since undefined
can be overwritten:
window.undefined = "foo";
"foo" == undefined // true
Note that in ECMAScript 5th edition, this has been patched, and undefined
is non-writable.
Using if (window.myVar)
is not robust because it includes falsy values like:
false
0
""
NaN
null
undefined
Additionally, the condition if (myVariable)
can throw an error in two scenarios. The first is when the variable hasn’t been declared, resulting in a ReferenceError
:
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
The second scenario is when the variable is defined but has a getter function that throws an error:
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
If a variable is undefined
, it will not be equal to a string containing the characters “undefined” since a string is not undefined
.
To check if a variable is defined, you can use the typeof
operator:
if (typeof something !== "undefined") ...
In some cases, you might not need to check the type. If the variable’s value cannot evaluate to false
when set (e.g., if it’s a function), you can directly evaluate the variable:
if (something) {
something(param);
}
This approach works well when the variable is expected to always have a truthy value when defined.
If you want to check if a variable foo
is undefined
, you can use the typeof
operator:
if (typeof foo == 'undefined') {
// Do something
}
It’s important to note that using strict comparison (!==
) is not necessary here because typeof
always returns a string.