Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the explanation for the strange javascript expression?

Tags:

javascript

In JavaScript the following line of code gives answer as 1

+ ! {} [true]

I couldn't understand how?

Any gurus explanation is appreciated.

like image 494
rajakvk Avatar asked May 10 '13 09:05

rajakvk


2 Answers

{} 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.

like image 191
Romain Braun Avatar answered Nov 15 '22 11:11

Romain Braun


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
like image 2
rab Avatar answered Nov 15 '22 10:11

rab