diff --git a/README.md b/README.md index 499930b..86b120e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_564 TILs and counting..._ +_565 TILs and counting..._ --- @@ -215,6 +215,7 @@ _564 TILs and counting..._ - [Globally Install A Package With Yarn](javascript/globally-install-a-package-with-yarn.md) - [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md) - [Initialize A New JavaScript Project With Yarn](javascript/initialize-a-new-javascript-project-with-yarn.md) +- [Matching Multiple Values In A Switch Statement](javascript/matching-multiple-values-in-a-switch-statement.md) - [Numbers Are Empty](javascript/numbers-are-empty.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) diff --git a/javascript/matching-multiple-values-in-a-switch-statement.md b/javascript/matching-multiple-values-in-a-switch-statement.md new file mode 100644 index 0000000..f423234 --- /dev/null +++ b/javascript/matching-multiple-values-in-a-switch-statement.md @@ -0,0 +1,28 @@ +# Matching Multiple Values In A Switch Statement + +Switch statements are a handy way to execute different branches of code +based on a value match. This is often what is used in Redux reducers when +updating the state in response to certain actions. + +But what if you need multiple values to result in the same branch of +execution without duplicating the code? + +The execution of a switch statement falls through, so after one match, it +will continue to try and do subsequent matches if you don't interrupt the +execution with a `break` or `return`. Conveniently, this solves our problem +of matching multiple values. + +```javascript +switch (action.type) { + case "UPDATE_NAME": + case "UPDATE_DURATION": + let newData = anotherReducer(state.data, action); + return { ...state, data: newData }; + default: + return state; +} +``` + +See the [MDN +docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) +for more details.