Remote Software Engineer at Stripe and cellist based out of Ontario. Previously at GitLab. Fascinated with building usable, delightful software.
November 16, 2018 | 2 minutes to read
One of the small but important features of ES6 is a shorthand syntax for creating object literals:
const person = { name, age, height, hairColor };
I can only assume this syntax sugar was added to the language because the ECMAScript gods were tired of looking at ES5 code like this:
const person = {
name: name,
age: age,
height: height,
hairColor: hairColor
};
This seems like an obvious win - why would you want to write six lines of code when you could just write one?
There’s one downside to this syntax that’s not immediately obvious. Let’s say you have some code like this:
getPerson() {
const height = 182;
// ... 100 more lines of code ...
return { name, age, height, hairColor };
}
After working with this code a bit, you realize that it’s not super clear what unit the height
variable uses, so you decide to use your editor’s auto-refactor feature to rename this variable from height
to heightInCm
:
getPerson() {
const heightInCm = 182;
// ... 100 more lines of code ...
But wait! By changing the name of an internal variable, you’ve now changed the public interface of your function!
// ... 100 more lines of code ...
return { name, age, heightInCm, hairColor };
}
If you’re not using a compile-safe language like TypeScript, you might forget to update the consumers of this function. Or even if you are using TypeScript, you might forget to update an HTML template that references this variable name. This has bitten me a few times in the past.
Like I said, it’s only kind of scary.
Other posts you may enjoy:
November 25, 2024 | 10 minutes to read
October 14, 2024 | 3 minutes to read
May 31, 2024 | 6 minutes to read
June 26, 2023 | 14 minutes to read
January 25, 2022 | 6 minutes to read