From f858a64aa73d27908833cbf9aa9c1c111d8c50af Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 15 Mar 2016 09:07:41 -0500 Subject: [PATCH] Add Object Initialization With Shorthand Property Names as a js til --- README.md | 3 +- ...alization-with-shorthand-property-names.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 javascript/object-initialization-with-shorthand-property-names.md diff --git a/README.md b/README.md index 3fb5392..1035ec1 100644 --- a/README.md +++ b/README.md @@ -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/). -_364 TILs and counting..._ +_365 TILs and counting..._ --- @@ -122,6 +122,7 @@ _364 TILs and counting..._ - [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) - [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md) +- [Object Initialization With Shorthand Property Names](javascript/object-initialization-with-shorthand-property-names.md) - [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md) - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) - [Throttling A Function Call](javascript/throttling-a-function-call.md) diff --git a/javascript/object-initialization-with-shorthand-property-names.md b/javascript/object-initialization-with-shorthand-property-names.md new file mode 100644 index 0000000..42379aa --- /dev/null +++ b/javascript/object-initialization-with-shorthand-property-names.md @@ -0,0 +1,39 @@ +# Object Initialization With Shorthand Property Names + +If I have some variables: + +```javascript +const one = 1, + two = 2, + three = 3; +``` + +and I'd like to initialize an object with them, I'll generally do something +like the following: + +```javascript +const obj1 = { + one: one, + two: two, + three: three +}; +// Object { one: 1, two: 2, three: 3 } +``` + +That seems pretty standard, but with ES6 comes a feature called *shorthand +property names* which makes that look verbose and redundant. If you already +have properly named variables, they can be used as a short hand for both the +key name and variable value: + +```javascript +const obj2 = { + one, + two, + three +}; +// Object { one: 1, two: 2, three: 3 } +``` + +See the [MDN Docs for Object +Initializer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) +for more details.