Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
ES6 Property Shorthands in JavaScript
ES6 introduced property shorthand syntax that simplifies object creation when the property name matches the variable name. Instead of writing name: name, you can simply write name.
Syntax
// ES5 way
let obj = {
property: property,
anotherProperty: anotherProperty
};
// ES6 shorthand
let obj = {
property,
anotherProperty
};
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6 Property Shorthands</title>
</head>
<body>
<h1>ES6 Property Shorthands in JavaScript</h1>
<div id="result"></div>
<button onclick="showPersonDetails()">Show Person Details</button>
<script>
function showPersonDetails() {
let name = 'Rohan';
let age = 16;
let place = 'Delhi';
// ES6 property shorthand
let person = {
name,
age,
place
};
let result = document.getElementById('result');
result.innerHTML = `
<p>person.name = ${person.name}</p>
<p>person.age = ${person.age}</p>
<p>person.place = ${person.place}</p>
`;
}
</script>
</body>
</html>
Comparison: ES5 vs ES6
let firstName = 'John';
let lastName = 'Doe';
let age = 30;
// ES5 way
let personES5 = {
firstName: firstName,
lastName: lastName,
age: age
};
// ES6 shorthand
let personES6 = {
firstName,
lastName,
age
};
console.log('ES5 object:', personES5);
console.log('ES6 object:', personES6);
console.log('Both are equal:', JSON.stringify(personES5) === JSON.stringify(personES6));
ES5 object: { firstName: 'John', lastName: 'Doe', age: 30 }
ES6 object: { firstName: 'John', lastName: 'Doe', age: 30 }
Both are equal: true
Mixed Usage Example
You can mix shorthand properties with regular properties in the same object:
let username = 'alice123';
let email = 'alice@example.com';
let user = {
username, // shorthand
email, // shorthand
isActive: true, // regular property
role: 'admin' // regular property
};
console.log(user);
{ username: 'alice123', email: 'alice@example.com', isActive: true, role: 'admin' }
Key Benefits
| Feature | ES5 | ES6 Shorthand |
|---|---|---|
| Code Length | Longer | Shorter |
| Readability | More verbose | Cleaner |
| Duplication | Property name repeated | No duplication |
Conclusion
ES6 property shorthand reduces code duplication and improves readability when object properties match variable names. This feature is widely supported and commonly used in modern JavaScript development.
Advertisements
