0

Try these in your browser's JS console:

{}['constructor']                      //==>  ['constructor']
{}['constructor'] === ['constructor']  //==>  false
console.log({}['constructor'])         //==>  function Object() { [native code] }

The first expression evaluated returns an array with a single item: 'constructor', However, the second expression seems to contradict the first by returning false. The third logs the Object constructor to the console.

Why are the second two expressions not consistent with the first?

24
  • Try [1] === [1] to see why the second one is false. Each array literal is a different array. Commented Jul 30, 2013 at 5:22
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 30, 2013 at 5:22
  • The third one gets the object literal's constructor property... Commented Jul 30, 2013 at 5:24
  • @Ian I see that, but why doesn't the first? Commented Jul 30, 2013 at 5:25
  • And I don't think the second one has anything to do with arrays. {}['constructor'] will be evaluated as an expression (which is what the third example shows). And obviously the constructor won't be equal to an array Commented Jul 30, 2013 at 5:26

1 Answer 1

3

Because

{}['constructor']

Is being parsed as

{
    // empty block
}
['constructor']

Try typing

var x = {}; x['constructor']

Or

({})['constructor']

And you will get the expected result. {} is always parsed as an empty block, except where it wouldn't make sense (like in the two examples above).

Barmar explains the second in the comments. In short, [1] !== [1] because they're two different array objects.

The third example works because JavaScript knows that you can't pass a block to a function, so it assumes an empty object instead.

Sign up to request clarification or add additional context in comments.

4 Comments

Try also ({})['constructor']
It's starting to make sense now. Is there some sort of guide that says when {} will be parsed as an object vs. a block?
@Web Always a block - unless it doesn't make sense to have a block there.
I just got taught! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.