In JavaScript the following line of code gives answer as 1
+ ! {} [true]
I couldn't understand how?
Any gurus explanation is appreciated.
{} 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With