ECMAScript 2015 introduced several syntactic enhancements to object literal notation, making object creation concise, expressive, and less repetitive.
1. Property Value Shorthand
Before ES6, assigning a variable to an object property with the same name required duplicating the identifier:
1const name ="Full-Stack Web Development";
2const duration ="12 Months";
3const price =49999;
4
5// The Old Way (ES5):
6const courseOld ={
7name: name,
8duration: duration,
9price: price
10};
11
12// The Enhanced ES6 Shorthand:
13const courseNew ={
14 name,
15 duration,
16 price
17};
If the property name matches the variable name, write it once!
2. Method Definition Shorthand
You can define methods without typing the function keyword or colon : :
1// The Old Way:
2const calculatorOld ={
3add:function(a, b){
4return a + b;
5}
6};
7
8// The Modern Shorthand:
9const calculatorNew ={
10add(a, b){
11return a + b;
12},
13subtract(a, b){
14return a - b;
15}
16};
3. Computed Property Names ([expression])
Before ES6, to create an object whose property key was dynamic or computed from an expression, you had to instantiate the object first and then use bracket notation on a separate line:
1// The Old Way:
2const prefix ="user_";
3const dynamicKey = prefix +"role";
4
5const userOld ={};
6userOld[dynamicKey]="admin";
With ES6 Computed Property Names:
You can calculate the property key directly inside the object literal using square brackets [...]:
1const prefix ="user_";
2const roleType ="admin";
3
4const userNew ={
5id:101,
6[`${prefix}status`]:"active",
7[`${prefix}role`]: roleType,
8[1+2]:"three"
9};
10
11console.log(userNew.user_status);// "active"
12console.log(userNew.user_role);// "admin"
13console.log(userNew[3]);// "three"
4. Real-World Use Case: Dynamic Form Handlers
Computed properties are universally used in form handlers (like React onChange events):
1functionhandleInputChange(fieldName, value){
2// Update state immutably using computed property: