Enhanced object literals are an ES6 feature that makes it easier to create JavaScript objects with shorter and more flexible syntax. They allow you to define properties using shorthand notation, write methods without the function keyword, and create property names dynamically using expressions.
Before ES6, developers often had to write extra code when creating objects from existing variables or defining methods. Enhanced object literals simplify these tasks and make code easier to read and maintain.
In this tutorial, you will learn about shorthand properties, shorthand methods, and computed properties with practical JavaScript examples.
What Are Enhanced Object Literals in JavaScript?
An object literal is a way to create an object using curly braces ({}). An object can contain properties and methods that describe its data and behavior.
For example:
const user = {
name: "Rahul",
age: 25,
greet: function() {
return "Hello!";
}
};
console.log(user.name);
console.log(user.greet());
Output:
Rahul
Hello!
ES6 introduced enhanced object literal syntax to make object creation more concise.
The main features include:
- Shorthand properties: Use a variable name directly as an object property.
- Shorthand methods: Define methods without writing
function. - Computed properties: Create property names using expressions.
To understand the fundamentals behind this feature, you can also explore JavaScript Objects.
Shorthand Properties in JavaScript
Shorthand properties allow you to create an object property using an existing variable when the variable name and property name are the same.
Before ES6, you had to write the property name and variable name separately. With shorthand properties, you can write the variable name only once.
Object Properties Before ES6
Consider the following example:
const name = "Rahul";
const age = 25;
const city = "Hyderabad";
const user = {
name: name,
age: age,
city: city
};
console.log(user);
Output:
{
name: "Rahul",
age: 25,
city: "Hyderabad"
}
Here, the property names and variable names are identical. The code works correctly, but it contains unnecessary repetition.
Using Shorthand Properties
ES6 allows you to shorten the same code.
const name = "Rahul";
const age = 25;
const city = "Hyderabad";
const user = {
name,
age,
city
};
console.log(user);
Output:
{
name: "Rahul",
age: 25,
city: "Hyderabad"
}
JavaScript automatically creates properties using the variable names as property names and their values as property values.
The following two expressions are equivalent:
const user = {
name: name
};
const user = {
name
};
Both create an object with a name property.
Practical Example of Shorthand Properties
Shorthand properties are especially useful when creating objects from form data, function parameters, or application variables.
function createProduct(name, price, category) {
return {
name,
price,
category
};
}
const product = createProduct("Laptop", 55000, "Electronics");
console.log(product.name);
console.log(product.price);
console.log(product.category);
Output:
Laptop
55000
Electronics
The function returns an object containing the values passed through its parameters.
Without shorthand properties, you would write name: name, price: price, and category: category. The shorter syntax avoids this repetition.
Important: Shorthand properties work when the variable name matches the desired property name. If the names differ, use the regular propertyName: value syntax.
const productName = "Laptop";
const product = {
name: productName
};
console.log(product.name);
Output:
Laptop
In this example, the variable is productName, but the object property is name, so the regular property syntax is required.
Shorthand Methods in JavaScript
Shorthand methods allow you to define functions directly inside an object without using the function keyword.
This syntax makes object methods shorter and easier to read.
Object Methods Before ES6
Before ES6, an object method was commonly written like this:
const user = {
name: "Rahul",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(user.greet());
Output:
Hello, Rahul
The greet method uses this.name to access the name property of the object.
Using Shorthand Methods
With ES6, you can remove the colon and function keyword.
const user = {
name: "Rahul",
greet() {
return "Hello, " + this.name;
}
};
console.log(user.greet());
Output:
Hello, Rahul
Both examples define a method named greet. The second example uses shorthand method syntax.
The general syntax is:
const object = {
methodName(parameters) {
// Method body
}
};
Multiple Shorthand Methods
An object can contain multiple shorthand methods.
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
multiply(a, b) {
return a * b;
}
};
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
console.log(calculator.multiply(10, 5));
Output:
15
5
50
Each method performs a different calculation. The shorthand syntax makes the object easier to read.
Using this in Shorthand Methods
Shorthand methods can use this to access other properties of the same object when called as object methods.
const employee = {
name: "Priya",
role: "Developer",
getDetails() {
return `${this.name} is a ${this.role}.`;
}
};
console.log(employee.getDetails());
Output:
Priya is a Developer.
Here, this.name accesses the employee’s name, and this.role accesses the employee’s role.
Unlike arrow functions, shorthand methods have their own this behavior. In a method call such as employee.getDetails(), this refers to employee.
For more information about function behavior and syntax, see JavaScript Functions.
Computed Properties in JavaScript
Computed properties allow you to create object property names dynamically using expressions. This feature is useful when the property name is stored in a variable or needs to be calculated.
In an object literal, you place the expression inside square brackets ([]).
Creating a Property from a Variable
Consider the following example:
const propertyName = "name";
const user = {
[propertyName]: "Rahul"
};
console.log(user);
console.log(user.name);
Output:
{
name: "Rahul"
}
Rahul
JavaScript evaluates propertyName and uses its value, "name", as the object’s property name.
Without square brackets, the property would literally be named propertyName, rather than using the value stored in that variable.
Using Expressions as Property Names
Computed properties can use expressions, not just variables.
const prefix = "user";
const profile = {
[prefix + "Name"]: "Priya",
[prefix + "Age"]: 24
};
console.log(profile.userName);
console.log(profile.userAge);
Output:
Priya
24
JavaScript evaluates each expression to determine the final property name.
In this example:
prefix + "Name"becomes"userName".prefix + "Age"becomes"userAge".
This is useful when building objects with property names based on application data.
Using Computed Properties in Functions
Computed properties are useful when you want to create an object whose property name depends on a function argument.
function createObject(key, value) {
return {
[key]: value
};
}
const user = createObject("name", "Rahul");
const product = createObject("price", 2500);
console.log(user);
console.log(product);
Output:
{ name: "Rahul" }
{ price: 2500 }
The function creates a property using the supplied key value. This makes the function reusable for different property names.
Combining Computed Properties with Methods
You can also use computed properties to define method names dynamically.
const methodName = "greet";
const user = {
name: "Rahul",
[methodName]() {
return `Hello, ${this.name}!`;
}
};
console.log(user.greet());
Output:
Hello, Rahul!
The expression [methodName] evaluates to "greet", so the object receives a method named greet.
Combining Enhanced Object Literal Features
You can use shorthand properties, shorthand methods, and computed properties together in a single object.
const name = "Rahul";
const age = 25;
const methodName = "getDetails";
const user = {
name,
age,
[methodName]() {
return `${this.name} is ${this.age} years old.`;
}
};
console.log(user);
console.log(user.getDetails());
Output:
{
name: "Rahul",
age: 25,
getDetails: [Function: getDetails]
}
Rahul is 25 years old.
The object uses shorthand properties for name and age, while the computed property creates the getDetails method dynamically.
The exact representation of a function inside an object may vary between JavaScript environments, but calling the method produces the shown sentence.
Shorthand Properties vs Shorthand Methods vs Computed Properties
| Feature | Purpose | Example |
|---|---|---|
| Shorthand properties | Use a variable name as the property name | { name } |
| Shorthand methods | Define methods without the function keyword | { greet() {} } |
| Computed properties | Calculate property names dynamically | { [key]: value } |
These features solve different problems, but all three help simplify object creation.
Common Mistakes to Avoid
Forgetting Square Brackets for Computed Properties
If you want to use the value of a variable as a property name, you must use square brackets.
const key = "name";
const user = {
[key]: "Rahul"
};
console.log(user.name);
Output:
Rahul
Without square brackets, key: "Rahul" creates a property literally named key.
Using Shorthand Properties with Different Variable Names
Shorthand properties require the variable name to match the property name.
const userName = "Priya";
const user = {
name: userName
};
console.log(user.name);
Output:
Priya
Use name: userName when the desired property name differs from the variable name.
Confusing Shorthand Methods with Arrow Functions
A shorthand method and an arrow function are not identical.
const user = {
name: "Rahul",
greet() {
return this.name;
}
};
console.log(user.greet());
Output:
Rahul
Shorthand methods have their own this behavior, while arrow functions inherit this from their surrounding scope. Choose the syntax that matches the behavior you need.
Frequently Asked Questions
What are enhanced object literals in JavaScript?
Enhanced object literals are ES6 features that simplify object creation using shorthand properties, shorthand methods, and computed property names.
What is a shorthand property?
A shorthand property lets you use an existing variable as an object property when both names are the same. For example, { name } is equivalent to { name: name }.
What is a shorthand method?
A shorthand method defines an object method without the function keyword. For example, greet() { return "Hello"; }.
What are computed properties?
Computed properties allow JavaScript to evaluate an expression to determine an object’s property name. For example, { [key]: value } uses the value stored in key as the property name.
Can computed properties use variables?
Yes. Computed properties can use variables, string expressions, and other valid expressions to determine property names dynamically.
Are enhanced object literals part of ES6?
Yes. Shorthand properties, shorthand methods, and computed property names were introduced in ECMAScript 2015, also known as ES6.
Conclusion
Enhanced object literals make JavaScript objects easier to create and maintain. Shorthand properties reduce repetition when variable and property names match, shorthand methods simplify function definitions inside objects, and computed properties allow dynamic property names.
These ES6 features are widely used in modern JavaScript applications. Understanding them will help you write more concise code and work more effectively with objects.
1 thought on “JavaScript Enhanced Object Literals”
Comments are closed.