0

From this MDN resource, the spread operator can be used for copying. I tried copying one object to another

const product1 = {'name': 'Pejeta Coffee Beans', 'price':500.00, 'category':'beverages'}

const product2 = {...product}

product1 === product2 //returns false

and after comparing the two objects, I got a false result. What could be the underlying reason fo this?

Skelli
  • 283
  • 2
  • 10
  • Two objects are *only* equal if they are *the same* object. The comparison operator doesn't take account the data they contain. – VLAZ May 04 '20 at 08:02

3 Answers3

1

Object comparison in JavaScript happens by reference, not by value. That means that the objects are only equal if they are the exact same object. Example:

const object1 = {a: 1};
const object2 = object1;
const object3 = {a: 1};

console.log(object1 === object2); // true
console.log(object1 === object3); // false
console.log(object2 === object3); // false
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
1

product2 and product1 aren't actually referring to the same object, so the equality check returns false.

You copied all fields from product1 into product2, so they now effectively have the same state, however, the objects themselves are still not the same.

MDN has some good reference on equality and sameness in JavaScript here

agschrei
  • 31
  • 2
0

It is not possible to check the equality of two objects using "===". What you could do is to check the equality using loadash _.IsEqual(product1, product2)

var _ = require('lodash');
const product1 = { 'name': 'Pejeta Coffee Beans', 'price': 500.00, 'category': 'beverages' }
const product2 = {...product1 }
console.log(_.isEqual(product1, product2))