Classes or Plain Objects
You now know two ways to make an employee: a plain object literal, or an instance of a class. Which one should you use? Programmers coming from Java or C# often put everything in classes. In JavaScript, the usual choice is different.
Plain objects are the default for data. Data that comes from outside (JSON from a server, a file, settings) is made of plain objects. So is most data that you only read and pass around. The tools from the Objects section (dot and bracket access, destructuring, spread, JSON) are all you need for it.
A class would not help here. JSON.parse always gives you plain objects, never instances of your class. Even if you stringify an instance, the copy that comes back from parse has lost its class and its methods:
class Employee {
constructor(name) {
this.name = name;
}
describe() {
return `I am ${this.name}`;
}
}
const alice = new Employee("Alice");
const text = JSON.stringify(alice);
const copy = JSON.parse(text);
console.log(alice);
console.log(copy);
console.log(copy.describe);
Output:
Employee { name: 'Alice' }
{ name: 'Alice' }
undefined
The copy prints without the class name, and copy.describe is undefined. The method did not survive the trip through JSON.
Use a class when the data has rules. Think of a shopping cart. A quantity must never be negative. The total must always match the items. Checkout must empty the cart. A class keeps these rules in one place: the constructor sets up a correct starting state, and the rest of the program changes the cart only through its methods. Other good uses are things with a life cycle, like a player in a game or a connection to a server.
There is also a middle way. Many programs use plain objects together with normal functions, like addToCart(cart, item) instead of cart.add(item). This style is common, and it is a good choice too. The mistakes are the two extremes: a class for every small record, or a cart with many rules but no single place that keeps them.
JavaScript itself uses both styles. Arrays, Maps and Sets are made by classes, which is why you write new Map(). Math and JSON are plain objects that hold useful functions.
This lesson has no coding exercise. Instead, answer a design question about a small shop.