Reputation: 10123
In JavaScript the following line of code gives answer as 1
+ ! {} [true]
I couldn't understand how?
Any gurus explanation is appreciated.
Upvotes: 7
Views: 132
Reputation: 4144
I tried to explain it through code .
var emptyObject = {};
valueOfUndefinedKey = emptyObject['key_not_exists'],
itsNot = !valueOfUndefinedKey ,
finalConvertedNumber = +itsNot ;
console.log(
emptyObject,
valueOfUndefinedKey,
itsNot,
finalConvertedNumber
)
which prints
Object {}
undefined
true
1
Upvotes: 3
Reputation: 3684
{}
is an empty object.
So {}[0]
or {}[true]
or {}[1]
etc.. are undefined
adding !
casts {}[0]
as a boolean
, returning the opposite. (undefined
becoming false
, it therefore returns true
).
adding +
casts it as an int
, so true
becomes 1
.
Upvotes: 5