- ES6 provides feature to support dynamic property name creation.
- A dynamic property can be defined using square bracket [].
- In this Demo, “We will learn to create a dynamic property of a JavaScript object”.
- The following code shows a student object aStudent containing 3 dynamic properties name,score and subject and static property country.
var property1 = "name", property2 = "score", property3 = "subject"; var aStudent = { [property1]:"Sandeep", [property2]:143, [property3]:"Computer", "country":"India" }; console.log("aStudent Name: ",aStudent.name); console.log("aStudent Score: ",aStudent.score); console.log("aStudent Subject: ",aStudent.subject); console.log("aStudent Country: ",aStudent.country);
- The output of the previous code can be found in below ES6 Fiddle.