diff --git a/README.md b/README.md index 5836210..f516a76 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/). -_751 TILs and counting..._ +_752 TILs and counting..._ --- @@ -265,6 +265,7 @@ _751 TILs and counting..._ - [Easy Date Comparison With DayJS](javascript/easy-date-comparison-with-dayjs.md) - [Expand Emojis With The Spread Operator](javascript/expand-emojis-with-the-spread-operator.md) - [Fill An Input With A Ton Of Text](javascript/fill-an-input-with-a-ton-of-text.md) +- [for...in Iterates Over Object Properties](javascript/for-in-iterates-over-object-properties.md) - [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md) - [Get The Location And Size Of An Element](javascript/get-the-location-and-size-of-an-element.md) - [Get The Time Zone Of The Client Computer](javascript/get-the-time-zone-of-the-client-computer.md) diff --git a/javascript/for-in-iterates-over-object-properties.md b/javascript/for-in-iterates-over-object-properties.md new file mode 100644 index 0000000..54aaf6e --- /dev/null +++ b/javascript/for-in-iterates-over-object-properties.md @@ -0,0 +1,30 @@ +# for...in Iterates Over Object Properties + +I don't reach for _for loops_ very often, so when I needed one recently I +thought I'd check out the newer `for...in` construct. It didn't behave quite +how I was expecting. I thought it would iterate over the values in the +target list, instead it seemed to be iterating over the indices. + +The [MDN +docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) +explain what is going on: + +> The `for...in` statement iterates over all non-Symbol, enumerable properties +> of an object. + +An array is an object whose properties are the indices of the values stored +in the array. + +```javascript +const fruits = ["apple", "banana", "orange"]; +for (let fruit in fruits) { + console.log(fruit, fruits[fruit]); +} +// => "0" "apple" +// => "1" "banana" +// => "2" "orange" +``` + +The iteration value wasn't what I was looking for, but in this case I can +use it to access the value from the list. I'd be better off using a standard +_for loop_ though.