ES6 Object Literal Shorthand Is Fun And Kind Of Scary

November 16, 2018  |  2 minutes to read


An ES6 object literal with two emojis in it


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?

The kind of scary part

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:

The Next Chapter

December 4, 2018  |  Less than 1 minute to read

Shell-ing With TypeScript

June 17, 2018  |  2 minutes to read

My First "Hello, World!"

June 7, 2018  |  5 minutes to read

Live Reloading An Angular 2+ App Behind NGINX

May 14, 2018  |  5 minutes to read

Fantastic Fast Fonts with system-ui

April 27, 2018  |  1 minute to read