Shanu Khera
Notes by Shanu Khera

Follow

Notes by Shanu Khera

Follow
Javascript notes - Part 4 - Shorthand syntax

Javascript notes - Part 4 - Shorthand syntax

Shorthand syntax for object properties and methods

Shanu Khera's photo
Shanu Khera
·Feb 20, 2021·

1 min read

Play this article

ES2015 introduced a shorthand syntax that is simply convenient syntactical sugar to write less, it helps developers write little more DRY code and is easy on the eyes once we know how it works.

function getUserInfo({name, email, isActive, lastLogin}) {

  return {
    userName: name,
    email: email,
    isActive: isActive,
    lastLogin: lastLogin,
    timestamp: Date.now(),
  }
}

Using shorthand property name syntax

function getUserInfo({name, email, isActive, lastLogin}) {
  // omitted the keys for which keys and values had same name
  return {
    userName: user.name,
    email,
    isActive,
    lastLogin,
    timestamp: Date.now(),
  }
}

Let's see another example this time an object that has a method too.

user = {
  name: "Shanu",
  location: "India",
  printIntro: function() {
    console.log("Learn to code with me 🚀")
  }
}

Using shorthand method syntax

user = {
  name: "Shanu",
  location: "India",
  printIntro () {
    console.log("Learn to code with me 🚀")
  }
}

Both of these syntactical sugar features make the object look very concise.

 
Share this