Home >Web Front-end >JS Tutorial >Computed Property Names in JavaScript: How Do Square Brackets Define Object Properties?
Unveiling Computed Property Names: What Lies Within the Square Brackets?
In the realm of JavaScript, where object literals reign supreme, a curious syntax has emerged: square brackets surrounding property names. This enigmatic notation, adorned as "computed property names," has recently graced the pages of ES6 specifications.
Enigmatically introduced in the example provided, the property dist holds sway over an inner object, with its files property hosting a peculiar syntactical specimen:
dist: { files: { [bpr + 'lib/Monster.min.js']: ['<%= concat.dist.dest %>'] } } }
Puzzled by this cryptic expression, we delve deeper into the enigmatic world of computed property names.
Demystifying Computed Property Names
As MDN illuminatingly proclaims: "Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name."
In essence, these square brackets grant us the power to dynamically generate property names based on the results of evaluated expressions. This ability proves invaluable when constructing object properties whose names cannot be determined statically.
Illuminating the Syntax
The syntax of computed property names is straightforward: enclose the expression that determines the property name within square brackets. This expression can range from simple variable references to complex computations:
const propertyName = 'age'; const object = { [propertyName]: 25 };
In this example, the property name is dynamically generated by the value of the propertyName variable.
Empowering Dynamic Object Construction
Computed property names empower the creation of dynamic objects where property names are determined at runtime. This flexibility becomes particularly useful when generating data structures based on external data or user input:
const data = { firstName: 'John', lastName: 'Doe', [`${firstName} ${lastName}`]: 'John Doe' };
This code dynamically creates a property using the concatenation of the firstName and lastName properties. The resulting object will have a property named "John Doe," making it easy to access the full name.
In Summary
Computed property names, introduced with ES6, elevate JavaScript's object construction capabilities by enabling dynamic property name generation through evaluated expressions. This flexibility unlocks a vast array of possibilities for constructing sophisticated and expressive object-based data structures.
The above is the detailed content of Computed Property Names in JavaScript: How Do Square Brackets Define Object Properties?. For more information, please follow other related articles on the PHP Chinese website!