Computed Properties
Version: ES2015
Level: Beginner
When using bracket notation ([]
) to access properties in an object, you can use any expression to represent the property key. This allows you to dynamically determine a key at runtime.
It used to be that this would only work off of existing objects, but starting with ES2015 this notation also became supported in object literals and class bodies. Properties using this syntax are known as computed properties.
let length = 0;
let fakeArray = {
[length++]: 'one',
[length++]: 'two',
[length++]: 'three',
length
};
console.log(fakeArray.length); // 3
console.log(fakeArray[1]); // two
Some properites require using computed property syntax, particularly those using symbols as keys. We’ve seen this before with symbols like Symbol.toStringTag
.
class Named {
get [Symbol.toStringTag] () {
return 'Named'
}
}
let named = new Named();
console.log(named.toString()); // [object Named]
This particular example uses defines a getter, but with class fields (stage 3 proposal), you can also define it as an instance field directly in the class body.
class Named {
[Symbol.toStringTag] = 'Named';
}
let named = new Named();
console.log(named.toString()); // [object Named]
Computed properties cannot be used with the property shorthand syntax that allows you to match keys and variables of the same name in scope. Attempting to do so will result in an error.
let prop = 'value';
let key = 'prop';
let obj = {
[key] // SyntaxError (not same as prop: prop)
};
More info: