Classes and Instances
An object literal like { name: "Alice", age: 34 } builds one object. When you need many objects with the same shape, you can write a class. A class is a plan for making objects. Each object made from it is called an instance of the class.
class Employee {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const a = new Employee("Alice", 34);
const b = new Employee("Bob", 41);
console.log(a.name, b.name);
Output:
Alice Bob
new Employee(...) creates a new, empty object. Then it runs the constructor, a special function inside the class, with the values you passed. Inside the constructor, this is the new object being set up. So this.name = name stores the name argument as a property of that object.
Each instance has its own properties. When you change Alice, Bob stays the same. console.log also shows the class name in front of an instance:
a.age = 35;
console.log(a);
console.log(b);
Output:
Employee { name: 'Alice', age: 35 }
Employee { name: 'Bob', age: 41 }
An instance is still an object. Everything from the Objects section works on it. You read and change properties with a dot, and you can put instances in an array and use filter, map or find on them:
const team = [a, b];
const older = team.filter(person => person.age > 40);
console.log(older);
Output:
[ Employee { name: 'Bob', age: 41 } ]
You have already used classes. Map and Set from the Objects section are classes that come with JavaScript. That is why you wrote new Map() and new Set().
You may see older code that makes objects with a normal function and new, without the class keyword. Classes were added to JavaScript later, as a clearer way to write the same thing. In new code, use class.
In the exercise, complete the constructor so it stores both values on this.