🥠Object Shorthands

In JavaScript, object shorthand is a shorthand syntax that can be used when defining object properties. It allows you to define properties in a more concise way.

Here is an example of how to define an object property using the traditional syntax:

let firstName = "John";
let lastName = "Doe";

let person = {
  firstName: firstName,
  lastName: lastName
};
console.log(person.firstName); // Output: "John"
console.log(person.lastName); // Output: "Doe"

With the shorthand syntax, you can omit the property value when the property name is the same as the variable name.

let firstName = "John";
let lastName = "Doe";

let person = {
  firstName,
  lastName
};
console.log(person.firstName); // Output: "John"
console.log(person.lastName); // Output: "Doe"

Shorthand can also be used when defining methods, instead of writing function keyword you can use the shorthand syntax by writing the name of the method and a pair of parentheses:

let person = {
  firstName: "John",
  lastName: "Doe",
  fullName() {
    return `${this.firstName} ${this.lastName}`
  }
}
console.log(person.fullName()); // Output: "John Doe"

In this way, you can use the shorthand syntax to make your code more concise and more readable, it can help you to avoid repeating yourself, and make the code more maintainable.

It's important to note that shorthand syntax only works when the property name is the same as the variable name, and it's only available when defining object literals, not when using the object constructor or object.create() method.

Last updated