1. Shallow copy vs Deep copy
Object.assign() or the spread operator (See below for more details). As you can see from this example, the
category property is unchanged in all cases. However, the
item property is changed when you clone an object using the spread operator, but not when you clone it using the deep copy methods.
Many people use
v8.deserialize(v8.serialize(obj)), but you cannot use this in a browser.
2. Take advantage of inline caching
The above two sets of code essentially do the same thing. The only difference is that the first example changes the shape of the object dynamically and the second example initializes the shape of the object at the beginning. These two approaches have different effects on compiler performance. In short, the first example creates lots of intermediate shapes of an object as you add more properties to the object. This makes it harder for JS compilers to apply inline caching. Especially if you are writing server-side code that frequently modifies the shape of the request object, then the effect on performance is not negligible. Whenever you find yourself adding a property dynamically, think about whether you can initialize the shape of an object. If you want to know more details about compiler optimization, you should read up on these resources:
3. Object.assign() vs Object spread operator
The differences between
Object.assign() and the spread operator is really subtle, and I’m pretty sure there are senior developers who are not aware of the exact differences. The biggest difference is that the spread operator defines properties, and
Object.assign() function invokes the set operator. This statement is not really helpful to understand when you should use one and not the other. If you want to just shallow copy an object, just use the spread operator all the time. If one of the properties of an object is read-only, then
Object.assign() does not let you shallow copy the object, but the spread operator does let you. If you want to learn more about the details, you should check out this blog post.
If you want to get reviews on your code and learn from reviews on other people’s code, we recommend that you check out what we’re building at Antcode and join our code review Slack group.