Home > Web Front-end > JS Tutorial > What's the Mystery Behind JavaScript's `{a, b, c}` Object Literal Shorthand?

What's the Mystery Behind JavaScript's `{a, b, c}` Object Literal Shorthand?

Susan Sarandon
Release: 2024-12-07 15:47:12
Original
935 people have browsed it

What's the Mystery Behind JavaScript's `{a, b, c}` Object Literal Shorthand?

An Alternative Look at Object Literals: Delving into the Enigma of {a, b, c}

Recent developments in JavaScript have introduced the enigmatic object literal property value shorthand syntax, particularly exemplified by the intriguing structure {a, b, c}. This snippet presents an intriguing departure from the familiar var g = {a: g, b: b, c: c} pattern.

Examining the Construct

To elucidate the nature of {a, b, c}, let's refer to the given JavaScript code snippet:

var a = 1, b = 'x', c = true;

var d = {a: a, b: b, c: c}; // Object literal
var e = [a, b, c]; // Array
var f = {a, b, c}; // Object literal property value shorthand
Copy after login

Interestingly, all three variable declarations yield identical output when their values are inspected using alert():

alert(d.a  + ', ' + d.b +  ', ' + d.c ); // Output: 1, x, true
alert(e[0] + ', ' + e[1] + ', ' + e[2]); // Output: 1, x, true
alert(f.a  + ', ' + f.b +  ', ' + f.c ); // Output: 1, x, true
Copy after login

Unveiling the Mystery

Introduced with ECMAScript 2015, the {a, b, c} syntax is a concise shorthand for var f = {a: a, b: b, c: c}. This shorthand notation, also referred to as property value shorthand, enables developers to streamline object literal definitions.

Moreover, it allows for seamless integration with traditional property initialization syntax:

var f = {a: 1, b, c};
Copy after login

In this instance, the property a is initialized explicitly with the value 1, while b and c utilize the shorthand notation.

For a deeper dive into the concept, refer to the documentation on Property definitions in Object initializer.

The above is the detailed content of What's the Mystery Behind JavaScript's `{a, b, c}` Object Literal Shorthand?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template