0

I have to match the following condition in my JavaScript code:

var a = [{}];

if (a === [{}]) {
  console.log('True');
} else {
  console.log('False');
}

it always prints False, why?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72
  • You can't compare an array, you could however use Lodash' `_.isEqual()` feature. `_.isEqual(a, [{}])`. This will compare the individual object and return true. – Jordec Mar 29 '19 at 14:37

1 Answers1

3

If you will compare two objects/arrays it will only return true if they have same reference in memory. [] will create a new array with different reference so it can't be equal to other.

console.log([] === []) //false

let a = [];
let b = a;
//Now 'a' and 'b' have same reference

console.log(a === b) //true

To solve this problem you can check length of array and length of Object.keys() of its first element.

var a = [{}];
if (a.length === 1 && typeof a[0] === "object" && Object.keys(a[0]).length === 0) {
   console.log('True');
} else {
   console.log('False');
}

You can also use JSON.stringify()

var a = [{}];
if (JSON.stringify(a) === '[{}]') {
   console.log('True');
} else {
   console.log('False');
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73