Shorthand Property and Method Names in JavaScript | ES6

1 min read.
This post is part of our Modern JavaScript course. Check it out, or don't.

In this video, you’ll learn how to make objects (both properties and methods) more concise with ES6’s “Shorthand Property” and “Shorthand Methods” features.

Video

Post

We are going to cover two features of ES6, short hand properties and method names. The whole point of both of these new features is to make objects more concise. Now, it is syntactical sugar so it’s not really necessary, but, it is nice.

Here, we have a “formatMessage” function which is going to take in a name, id, and avatar. All we’re doing is returning an object with each of those arguments as a property name on the object as well as a timestamp. The first feature we’ll be covering is ES6’s “Shorthand Property Names”. Here we have three properties whose keys are the exact same as their values.

function formatMessage (name, id, avatar) {
  return {
    name: name,
    id: id,
    avatar: avatar,
    timestamp: Date.now()
  }
}

When that’s the case, you can just delete the keys. So we can get rid of name, id, and avatar.

function formatMessage (name, id, avatar) {
  return {
    name,
    id,
    avatar,
    timestamp: Date.now()
  }
}

Again, if the key, or the property name is the exact same as the value, you can omit the key itself.

Now, what if one of these properties was a function? A function that is a property of an object is called a method. Here we have a method called “save” which is going to save the actual message. When we add a method to an object, we have a property and set that equal to a function expression, as we’re doing below.

function formatMessage (name, id, avatar) {
  return {
    name,
    id,
    avatar,
    timestamp: Date.now(),
    save: function () {
      //save message
    }
  }
}

With ES6’s “Shorthand Method Names”, we can omit the function keyword itself. So now, the code can now look like this.

function formatMessage (name, id, avatar) {
 return {
   name,
   id,
   avatar,
   timestamp: Date.now(),
   save () {
     //save message
   }
 }
}

Again, both of these features are just making objects more concise.

Liked this post? Share it 🕺

Newsletter

Listen, I get it, newsletters are the worst.

This one is different though.

Stay up to date with the latest and greatest in the JavaScript ecosystem.

Already a member? Enter your email to check your score.

The Socials

The Newsletter