JavaScript object literal shorthand syntaxJavaScript Object Literal Shorthand Syntax is a feature that provides a path to cleanerJavaScript. Not only does it provide a way to reduce the size of your code, but it will be easier to read and understand.

Many ECMAScript 2015 features provide improved ways to solve problems. Object literal shorthand syntax is a bit unique in that it’s not so much a shiny new tool, but an improved syntax. Now it might be tempting to dismiss this kind of feature as less-than-stellar, but it’s worth working into your routine for a number of reasons. For example, an improved syntax can lead to less code, and not only that, the code you write can be easier to understand. And believe me, those who inherit your code will thank you for this. So, in this article, I’ll explain how to use object literal shorthand syntax when defining properties and methods.

Typical Object Literal Syntax – Example # 1

See the Pen JavaScript Object Literal Shorthand Syntax – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

Let’s start with the way we’re used to working with object literals. In Example # 1 we have a getGoods() method that returns an object. The value argument is used on execution to set the value property, and the lowerValue() and raiseValue() methods lower and raise that value property. So this is all fine and everything works exactly as expected. In fact, if you look at the UI, the text that you see shows that our methods set and value property accordingly. Unlike many of the examples in this blog, there is nothing to “fix” here. Our code works fine and follows a typical syntax pattern because, as stated, I mainly wanted to establish that this is the way we normally work with object literals.

Object Literal Shorthand Syntax -Example # 2

See the Pen JavaScript Object Literal Shorthand Syntax – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, in Example # 2 we do things quite differently. To start, look at Line # 3. When we set the value property, there is no colon; we simply assign the value of the “value” argument that was provided when the function was executed. This syntax is concise, thereby requiring you to write less code. Now it may seem like a very small savings here, but when you have an application with many thousands of lines of code, the savings quickly add up.

Okay, so next, look at where we define the lowerValue() and raiseValue() methods. Here, notice two things are missing: there is no colon, and we don’t need the function keyword. We simply provide the parentheses and the curly braces (as well as the code inside the curly braces). Here, too, the savings may seem small on a per-line basis, but in a large application, the difference will be dramatic. And the additional benefit, especially when defining methods, is that the code is a bit easier to read.