Understanding Brackets in Object Literal Property Names
In JavaScript, object literals are commonly used to represent data as key-value pairs. However, a less familiar syntax involves square brackets surrounding property names. Let's explore the significance of this syntax.
Computed Property Names
Introduced in ES6, square brackets allow for the creation of computed property names. Unlike traditional property names that are static strings, computed property names can be dynamic expressions, evaluated at runtime.
Example:
dist: { files: { [bpr + 'lib/Monster.min.js']: ['<%= concat.dist.dest %>'] } } }
In this example, the property name is dynamically generated using the expression bpr 'lib/Monster.min.js'. This feature enables you to define property names based on dynamic variables or other computations.
Use Cases
Computed property names are particularly useful when:
MDN Definition
The Mozilla Developer Network (MDN) defines computed property names as:
"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."
The above is the detailed content of When and Why Use Square Brackets in Object Literal Property Names?. For more information, please follow other related articles on the PHP Chinese website!