mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 16:18:01 +00:00
Add Computed Property Names In ES6 as a JavaScript til
This commit is contained in:
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
|
||||
warrant a full blog post. These are mostly things I learn by pairing with
|
||||
smart people at [Hashrocket](http://hashrocket.com/).
|
||||
|
||||
_360 TILs and counting..._
|
||||
_361 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -118,6 +118,7 @@ _360 TILs and counting..._
|
||||
### JavaScript
|
||||
|
||||
- [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md)
|
||||
- [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md)
|
||||
- [Create An Array Containing 1 To N](javascript/create-an-array-containing-1-to-n.md)
|
||||
- [Enable ES7 Transforms With react-rails](javascript/enable-es7-transforms-with-react-rails.md)
|
||||
- [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md)
|
||||
|
||||
37
javascript/computed-property-names-in-es6.md
Normal file
37
javascript/computed-property-names-in-es6.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Computed Property Names In ES6
|
||||
|
||||
Perhaps more often than not, property names in an object are based on
|
||||
something dynamic rather than a static value. In ES5, you may end up with
|
||||
code like the following to build an object with dynamic property names:
|
||||
|
||||
```javascript
|
||||
var dynamic1 = 'hello',
|
||||
dynamic2 = 'world';
|
||||
var obj = {};
|
||||
var propName1 = dynamic1 + dynamic2;
|
||||
var propName2 = 5 * 11;
|
||||
obj[propName1] = true;
|
||||
obj[propName2] = false;
|
||||
|
||||
> obj
|
||||
// { 55: false, 'helloworld': true }
|
||||
```
|
||||
|
||||
With ES6, we get _computed property names_ which allow us to do all of these
|
||||
inline when defining the object. We just have to wrap the code that will be
|
||||
evaluated to a property name in brackets:
|
||||
|
||||
```javascript
|
||||
const dynamic1 = 'hello',
|
||||
dynamic2 = 'world';
|
||||
const obj = {
|
||||
[dynamic1 + dynamic2]: true,
|
||||
[5 * 11]: false
|
||||
};
|
||||
|
||||
> obj
|
||||
// { 55: false, 'helloworld': true }
|
||||
```
|
||||
|
||||
Computed properties are [already available in many modern
|
||||
browsers](https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties).
|
||||
Reference in New Issue
Block a user