JavaScript Object Shorthand Properties Tutorial

In this section, we will learn what the object shorthand property is and how to use it in JavaScript.

What is Shorthand Properties in JavaScript?

There are times that we have a variable with a value in a scope but also want to have the same name and value as the property of an object.

In situations like this, the shorthand property can become super handy and helpful.

The shorthand property concept refers to the fact that we can use the name of a variable inside an object instead of duplicating and writing that name and value in that object again.

Example: creating shorthand properties in JavaScript

let name = "John";
let lastName = "Doe";
const obj = {
  name,
  lastName
}
console.log(obj.name, obj.lastName);

Output:

John Doe

How to Create Shorthand Properties in JavaScript?

In this example, there are two variables `name` and `lastName`. Also, there’s an object named `obj`.

In this object we also need two properties with the names `name` and `lastName` and the values `John` and `Doe` respectively.

So the traditional way to do this would be:

const obj = {
   name: "John",
    lastName: "Doe"
}

If you think about it, here we’re repeating ourselves! This is because there are two variables with exact names and values already declared in the program.

So in situations like this, we can directly use those external variables in the target object (obj in this case) instead of rewriting them as the properties of this object.

Using this method has the same effect as if we were adding the properties and values manually into the target object.

So the object `obj` in the example above will be automatically translated from:

const obj = {
        name,
        lastName
      }

To:

const obj = {
   name: "John",
    lastName: "Doe"
}

Using shorthand properties basically helps developers to write objects in shorter way as well as faster.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies