I do not know exactly why this works, but what I noticed is that the exception of an undefined variable helps us to find out if it exists or not, whether global or local.
try {
aa
} catch(e) {
// não existe
}
For object properties this makes it difficult to detect the presence of a property in old browsers (type MsIE6), but thanks to the in
operator this makes it possible, with one exception.
Anyway, it would not make sense for a non-existent property to throw an exception, perhaps they wanted to avoid problems with expressions:
!!b
Only one exception to be thrown, the execution of that block for, unless there is a try/catch/finally
to protect the exception.
Currently, to find out whether an object's property exists we need a native method or operator, the property can be undefined
, any type of value. Object#hasOwnProperty
resolves this, the in
operator will do the same, but will deeply check if the specific property exists in the constructor properties, too.
Warning1: name of all properties of an object / function are converted to string;
Warning²: both functions and objects can save properties on itself;
Warning: all numeric values, strings, objects, functions, and booleans can be indexed .
or [...]
, minus null
and undefined
-
var a = {
b: undefined
}
// Diz que a.b não existe
typeof a.b !== 'undefined'
// Diz que a.b existe
a in 'b'
// Diz que a.b existe
a.hasOwnProperty('b')
And this is the most commonly used way to check if a property exists:
// Se a.b for um valor verdadeiro,
// diz sim
!!a.b