2
new Array // outputs []

[] // outputs []

But new Array === [] is false. Why so?

console.log(new Array === [])
Axel
  • 4,365
  • 11
  • 63
  • 122

2 Answers2

6

Because they are two different references. They can be two arrays with no elements, but they are two completely different objects on the heap.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • Maybe I am understanding it wrong but `typeof new Array === typeof []` is still true!!! – Axel Nov 13 '18 at 14:35
  • 4
    @Sanjay yes, you are understanding it wrong. Your question's example is comparing two separate objects, but in your comment you're testing the type. – j08691 Nov 13 '18 at 14:37
  • @Sanjay what does `typeof` ? *The typeof operator returns a string indicating the type of the unevaluated operand*, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof. That being said it is clear why the above expression is true. – Christos Nov 13 '18 at 14:38
  • `two completely different objects` This sentence puzzled me haha – Axel Nov 13 '18 at 14:38
  • because `typeof` returns a `string`, and they are two objects, so `("object"==="object")` is true – eag845 Nov 13 '18 at 14:38
  • @Sanjay In the code in your question, `new Array === []`, you're asking 'JavaScript, create a new array for me, is identical to, JavaScript, create *another* new array for me'. Yes, they are both arrays (which is why typeof returns true) but they're not identical or referring to the same array. – j08691 Nov 13 '18 at 14:42
  • @Sanjay let that we have `var a = [];` What `a` holds ? `a` holds a reference to an object in heap - a place in memory that have been reserved from your program. Whenever you need to access this object you do so through it's reference e.g. by using `a`. If you want to append an item in this array, `a.push(1)` etc. In the same lines `new Array` creates another array and returns a reference to that array. So when you call `new Array` and then you use the `[]` you create two objects in the heap. – Christos Nov 13 '18 at 14:42
  • @Christos Thanks for your time! Got it! – Axel Nov 13 '18 at 15:04
  • @Sanjay you are very welcome. I am glad that I helped :) – Christos Nov 13 '18 at 15:22
0

Because you are constructing two empty Arrays on each side of the comparison. They are not referring to the same array.

hktang
  • 1,745
  • 21
  • 35