diff --git a/README.md b/README.md index 8e5b48f..b31ed0a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1227 TILs and counting..._ +_1228 TILs and counting..._ --- @@ -439,6 +439,7 @@ _1227 TILs and counting..._ - [Sleep For A Bit In Async Code](javascript/sleep-for-a-bit-in-async-code.md) - [Sorting Arrays Of Objects With Lodash](javascript/sorting-arrays-of-objects-with-lodash.md) - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) +- [Spread Merging Objects Includes Nil Values](javascript/spread-merging-objects-includes-nil-values.md) - [Spread The Rest With ES6](javascript/spread-the-rest-with-es6.md) - [Start Node Process In Specific Timezone](javascript/start-node-process-in-specific-timezone.md) - [String Interpolation With Template Literals](javascript/string-interpolation-with-template-literals.md) diff --git a/javascript/spread-merging-objects-includes-nil-values.md b/javascript/spread-merging-objects-includes-nil-values.md new file mode 100644 index 0000000..193bf43 --- /dev/null +++ b/javascript/spread-merging-objects-includes-nil-values.md @@ -0,0 +1,27 @@ +# Spread Merging Objects Includes Nil Values + +A handy way to merge two objects together with ES6 JavaScript syntax is to use +the [spread +operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). + +```javascript +const combinedObj = { ...obj1, ...obj2 }; +``` + +All the key-value pairs from each object are combined into a new object. For +any overlapping keys, the last occurrence's value will take precedence. + +That bit about precedence is true for _nil_ values – `null` and `undefined` – +as well. + +```javascript +const obj1 = { taco: 'bell', hello: 'world', list: [1,2,3] } +const obj2 = { burrito: 'house', hello: null, list: undefined } + +const combinedObj = { ...obj1, ...obj2 } +//=> { taco: 'bell', hello: null, list: undefined, burrito: 'house' } +``` + +Notice that even though there are "actual" values for the `hello` and `list` +keys in `obj1`, they are overridden by the `null` and `undefined` values in +`obj2`.