Reduce Code with Object Shorthand Syntax
Version: ES2015
Level: Beginner
Object literals ({}
) offer a couple of shortcuts that allow you to simplify and reduce redundancy in your code. The first we’ll look at is a shorthand for assigning properties in a new object to variables of the same name in the available scope. Not using this shorthand syntax, you’d have something like:
let wantsToBeAProperty = true;
let holderOfProperties = {
wantsToBeAProperty: wantsToBeAProperty
};
This creates a wantsToBeAProperty
property on the holderOfProperties
object with a value equal to the value in the variable wantsToBeAProperty
(true). The problem is, this code is redundant, causing you to write out wantsToBeAProperty
twice for the property, once for the key and once for the value. With the property shorthand syntax, you’ll only need to refer to it once.
let wantsToBeAProperty = true;
let holderOfProperties = {
wantsToBeAProperty
};
Simply including the property name without a colon (:
) and a respective value, JavaScript will automatically give it the value of the variable of the same name.
Functions, or object methods, also have a shorthand syntax. Normal method properties include the property name followed by a function expression as a value.
let doerOfThings = {
doAThing: function () {
// does a thing...
}
};
Using the method shorthand syntax, we can drop the colon (:
) and the function
keyword allowing us to more simply write:
let doerOfThings = {
doAThing () {
// does a thing...
}
};
This creates a function much like before, but without requiring as much code. In fact, if you’re familiar with class
syntax, you may recognize this is the same syntax used for class methods there.
More info: