What Removing Object Properties Tells Us About JavaScript — Smashing Magazine
A group of contestants are asked to complete the following task:
Make object1 similar to object2.
let object1 = { a: "hello", b: "world", c: "!!!", }; let object2 = { a: "hello", b: "world", };
Seems easy, right? Simply delete the c property to match object2. Surprisingly, each person described a different solution:
- Contestant A: “I set c to undefined.”
- Contestant B: “I used the delete operator.”
- Contestant C: “I deleted the property through a Proxy object.”
- Contestant D: “I avoided mutation by using object destructuring.”
- Contestant E: “I used JSON.stringify and JSON.parse.”
- Contestant F: “We rely on Lodash at my company.”
An awful lot of answers were given, and they all seem to be valid options. So, who is “right”? Let’s dissect each approach.
Contestant A: “I Set c To undefined.”
In JavaScript, accessing a non-existing property returns undefined.
const movie = { name: "Up", }; console.log(movie.premiere); // undefined
It’s easy to think that setting a property to undefined removes it from the object. But if we try to do that, we will observe a small but important detail:
const movie = { name: "Up", premiere: 2009, }; movie.premiere = undefined; console.log(movie);
Here is the output we get back:
{name: 'up',...
source: https://news.oneseocompany.com/2023/10/23/what-removing-object-properties-tells-us-about-javascript-smashing-magazine_2023102351665.html
Your content is great. However, if any of the content contained herein violates any rights of yours, including those of copyright, please contact us immediately by e-mail at media[@]kissrpr.com.