Square Brackets Javascript Object Key
It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey]
assignment that you know from ES3/5:
var a = "b"
var c = {[a]: "d"}
is syntactic sugar for:
var a = "b"
var c = {}
c[a] = "d"
Why put an object key in square brackets (not destructuring)?
This is a computed property - it's the equivalent of:
let result = {}
result[CALL_API] = { ... };
return result;
Combining this with Symbol
lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call
for their (unrelated) protocols - as well as colliding with Function.prototype.call
.)
What is the significance of double square brackets in javascript property names when initializing the object?
In ES6, [expression]: value
is interpreted as follows:
- evaluate
expression
- convert the result to a string
- use this string as a key
Respectively,
given [ [a] ]: 'boo'
evaluate [a] => ['foo']
String ['foo'] => 'foo'
result => {'foo': 'boo'}
In other words, extra brackets are ignored.
Related Topics
Detect Double Tap on iPad or iPhone Screen Using JavaScript
Fcm - Programmatically Send Push Notification to User Segments
Jquery-Ui Datepicker Change Z-Index
Detecting by How Much User Has Scrolled
Difference Between Statement and Function
Working Twitter-Typeahead Example
Smoothly Stop CSS Keyframe Animation
Retrieving Percentage CSS Values (In Firefox)
Jquery Draggable with Zoom Problem
Getting the Values of All the CSS Properties of a Selected Element in Selenium
Using JavaScript to Mark a Link as Visited
Multiline Typewriter Effect with Two Consistent Words
How to Generate an APK That Can Run Without Server with React-Native
Wait for Background Images in CSS to Be Fully Loaded
How to Use Materialize-CSS with Angular
Decoding Url Parameters with JavaScript
HTML - How to Show Tooltip Only When Ellipsis Is Activated
How to Split a Long Array into Smaller Arrays, with JavaScript