diff --git a/README.md b/README.md index f2d28f7..788255e 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/). -_646 TILs and counting..._ +_647 TILs and counting..._ --- @@ -251,6 +251,7 @@ _646 TILs and counting..._ - [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md) - [Render An Array Of Elements With React 16](javascript/render-an-array-of-elements-with-react-16.md) - [Running ES6 Specs With Mocha](javascript/running-es6-specs-with-mocha.md) +- [Scoping Variables With A Block Statement](javascript/scoping-variables-with-a-block-statement.md) - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) - [Spread The Rest With ES6](javascript/spread-the-rest-with-es6.md) - [String Interpolation With Template Literals](javascript/string-interpolation-with-template-literals.md) diff --git a/javascript/scoping-variables-with-a-block-statement.md b/javascript/scoping-variables-with-a-block-statement.md new file mode 100644 index 0000000..be417cd --- /dev/null +++ b/javascript/scoping-variables-with-a-block-statement.md @@ -0,0 +1,32 @@ +# Scoping Variables With A Block Statement + +A solid way to keep code readable and easy to understand is to ditch the +terse one-liners in favor of breaking things up across multiple lines and +using self-documenting variable names. This isn't all good though. Each new +variable that is defined is a handle on some data that can be misused later +in the syntax scope. + +JavaScript has a nice way of being clear about the scope of certain +variables: + +```javascript +let parsedDate; +{ + let [month, day, year] = input.split('-'); + parsedDate = new Date(year, month, day); +} + +// do something with parsedDate +``` + +The `month`, `day`, and `year` variables are scoped to the `{ ... }` which +is a [block +statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block). +This helps communicate and enforce that those variables are only to be used +in that very specific context. Other developers and our future selves won't +be able to erroneously use those variables. + +Of course, breaking out a function is another way of accomplishing this. +Sequestering code in a different part of the file is not always the best +answer though. Sometimes you want it locally fenced off. For those times, +use a block statement.