I don’t know exactly why it works like this, but what I’ve noticed is that the exception of an undefined variable helps us find out if it exists or not, whether it’s 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 older browsers (type Msie6), but thanks to the operator in
this makes it possible, with one exception.
Anyway, it wouldn’t make sense for a non-existent property to make an exception, maybe they wanted to avoid problems with expressions:
!!b
Only from an exception be launched, the execution of that block to, there is not be a try/catch/finally
to protect the exception.
Currently, to find out if the property of an object exists we need a native method or operator, the property can be undefined
, any kind of value. Object#hasOwnProperty
solves this, the operator in
will do the same, only that deep, will verify if the specific property exists in the properties of the builders, also.
Warning¹: the name of all properties of an object/function are converts for string;
Notice²: both of them function and objects can keep properties in itself;
Warning³: all numeric values, strings, objects, functions and booleans can be indexed .
or [...]
, least 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
After lunch, I vote :p
– Wallace Maxters