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?
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?
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');
}