-9

I saw this strange piece of code !{}[true]; today. When you run this code snippet, it returns true.

What full !{}[true] means and why it returns true.

>>>!{}[true];
'true'
Varun
  • 1,013
  • 3
  • 17
  • 28
  • Why do you have to ask a question that was asked barely a few hours back? – devnull Oct 31 '13 at 14:41
  • 1
    This was asked only 5 hours ago: http://stackoverflow.com/questions/19702805/why-does-true-evaluate-to-true-in-javascript – darthmaim Oct 31 '13 at 14:41
  • my bad, I did a Google search and didn't find answer at that time, that's why posted. and now I lost 5 points of my meager 126 :( – Varun Oct 31 '13 at 15:10
  • 1
    U can remove this question to restore ur points. As already indicated, it has been answered just a few hours back. – ND_27 Oct 31 '13 at 19:03

2 Answers2

2

{}[true] returns undefined because {} has no property "true" (!{"true":25}[true] would return false).

So !{} is true.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Negate an object? How exactly do you negate an object?

In any case, start with {}[true]. What that does is create a new object, and reference its true member, which doesn't exist, so returns undefined.

So then you have !undefined, which evaluates to true.

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
  • 1
    *"How exactly do you negate an object?"* All JavaScript values have a Boolean equivalent, so all values can be negated. – Blue Skies Oct 31 '13 at 14:45
  • @BlueSkies True. The object would be truthy, so negating would be false. The phrase made me think there was some other intent, and I didn't stop to think it through. – Scott Mermelstein Oct 31 '13 at 14:46
  • I think we can negate, `var obj = { one: 1, two: 2 }; >>>!obj >>>false' – Varun Oct 31 '13 at 14:48
  • 1
    @Varun Only in the sense Blue Skies and I mentioned. It's not invalid syntax, but I was curious if your understanding matched what happens. You can put `if (myObject)` as an if statement, and it will return true as long as myObject is not undefined or null (or an empty string or a zero number). You can't exactly negate an object, but you can negate the logical evaluation of one. That is, `myObject = !myObject` is not a syntax error, but almost certainly doesn't do what you want. And in this example, it wouldn't follow the typical rule of negation, that `!!object === object`. – Scott Mermelstein Oct 31 '13 at 14:52
  • 1
    @Varun `if (!myObject)` would look at the truthiness of `if (myObject)` and negate that, returning a boolean. If you did do something like `myObject = !myObject`, and myObject wasn't originally a boolean, you'd be taking an object and converting it to false. You may have known all that, but the phrase "negate an object" made me wonder. – Scott Mermelstein Oct 31 '13 at 14:56
  • 1
    I am learning Javascript and your explanation made few things clear, thanks a lot. – Varun Oct 31 '13 at 15:08