Comparing Objects in OOP in JavaScript
Let's see how variables containing objects are compared. Two variables will be considered equal if they contain a reference to the same object. Let's see in practice. Let's say we have the following class:
class User {
constructor(name) {
this.name = name;
}
}
Let's create two objects of this class:
let user1 = new User('1');
let user2 = new User('2');
Let's compare variables that contain a reference to the same object:
console.log(user1 === user1); // true
Now let's compare variables containing references to different objects:
console.log(user1 === user2); // false
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = new Employee('eric');
console.log(emp1 === emp2);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = new Employee('eric');
console.log(emp1 === emp1);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = new Employee('john');
console.log(emp1 === emp2);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = new Employee('eric');
console.log(emp1 !== emp1);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = emp1;
console.log(emp1 === emp2);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = new Employee('eric');
console.log(emp1 !== emp2);
Tell me what the result of the comparison will be in the following code:
class Employee {
constructor(name) {
this.name = name;
}
}
let emp1 = new Employee('john');
let emp2 = emp1;
emp2.name = 'eric';
console.log(emp1 === emp2);