0

I got this javaScript test but I can´t explain why the console give the answer it is giving. Can anyone explain this?

const obj1 = { c: 'c' };
const obj2 = { a: 1, b: [1], c: obj1 };
const obj3 = { a: 1, b: [1], c: obj1 };

console.log(obj2 === obj3);
console.log(obj2.a === obj3.a);
console.log(obj2.b === obj3.b);
console.log(obj2.c === obj3.c);

Output

false  
true  
false  
true
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 1
    Objects are compared using their references - not the key-value pairs inside them. This means that two different objects will never be equal to each other; this explains why 1st and 3rd console statements output `false` and why the 4th console statement outputs `true`. Primitive values are compared using their values, so `1 === 1` will always evaluate to true. – Yousaf Mar 09 '21 at 13:15
  • The short answer is that === does a "shallow" compare, only testing whether the operands are references to the same object. This is true for objects and arrays in JS, strings and numbers are compared by value. So `[1] === [1]` is `false`, because these are two _different_ arrays, just looking the same. Contrast with `var x = [1]; var y = x; x === y` which will produce `true`. – Jan Pokorný Mar 09 '21 at 13:17
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/229689/discussion-on-question-by-nathalie-nordstrom-explaining-the-functions-result). – deceze Mar 09 '21 at 14:43

0 Answers0