Here's some complaining a quick overview of some code that has confounded me more than once. I'm told even very experienced developers encounter these situations regularly, so if you find yourself on your third cup of coffee scratching your head over why your code is doing exactly what you told it to do (and not what you want it to do), maybe this post can help you.
The example code is JavaScript, since that's what I've been working in lately, but I believe the concepts to be pretty universal. (This article's original title was "JavaScript Sucks" but I decided I didn't want to invite that debate...)
Given a breakfast object that looks like this:
var breakfast = {
'eggs': 2,
'waffles': 2,
'fruit': {
'blueberries': 5,
'banana': 1,
},
'coffee': 1
}
Iterate over object properties
We can iterate through each breakfast item using a for loop as follows:
for (item in breakfast) {
console.log('item: ', item);
}
This produces:
item: eggs
item: waffles
item: fruit
item: coffee
Get object property value
We can access the value of the property or nested properties (in this example, the number of items) like this:
console.log('How many waffles? ', breakfast['waffles'])
console.log('How many bananas? ', breakfast['fruit']['banana'])
Or equivalent syntax:
console.log('How many waffles? ', breakfast.waffles)
console.log('How many bananas? ', breakfast.fruit.banana)
This produces:
How many waffles? 2
How many bananas? 1
Get object property from the value
If instead I want to access the property via the value, for example, to find out which items are served in twos, I can do so by iterating like this:
for (item in breakfast) {
if (breakfast[item] == 2) {
console.log('Two of: ', item);
}
}
Which gives us:
Two of: eggs
Two of: waffles
Alter nested property values
Say I want to increase the number of fruits in breakfast, because sugar is bad for me and I like things that are bad for me. I can do that like this:
var fruits = breakfast['fruit'];
for (f in fruits) {
fruits[f] += 1;
}
console.log(fruits);
Which gives us:
{ blueberries: 6, banana: 2 }
Arrays
Given an array of waffles that looks like this:
var wafflesIAte = [ 1, 3, 2, 0, 5, 2, 11 ];
Iterate through array items
We can iterate through each item in the array using a for loop:
for (var i = 0; i < wafflesIAte.length; i++) {
console.log('array index: ', i);
console.log('item from array: ', wafflesIAte[i]);
}
This produces:
array index: 0
item from array: 1
array index: 1
item from array: 3
array index: 2
item from array: 2
array index: 3
item from array: 0
array index: 4
item from array: 5
array index: 5
item from array: 2
array index: 6
item from array: 11
Some things to remember:
i
in the above context is a placeholder; we could substitute anything we like (x
, n
, underpants
, etc). It simply denotes each instance of the iteration.
i < wafflesIAte.length
tells our for loop to continue as long as i
is less than the array's length (in this case, 7).
i++
is equivalent to i+1
and means we're incrementing through our array by one each time. We could also use i+2
to proceed with every other item in the array, for example.
Access array item by index
We can specify an item in the array using the array index, written as wafflesIAte[i]
where i
is any index of the array. This gives the item at that location.
Array index always starts with 0
, which is accessed with wafflesIAte[0]
. using wafflesIAte[1]
gives us the second item in the array, which is "3".
Ways to get mixed up over arrays
Remember that wafflesIAte.length
and the index of the last item in the array are different. The former is 7, the latter is 6
.
When incrementing i
, remember that [i+1]
and [i]+1
are different:
console.log('[i+1] gives next array index: ', wafflesIAte[0+1]);
console.log('[i]+1 gives index value + 1: ', wafflesIAte[0]+1);
Produces:
[i+1] gives next array index: 3
[i]+1 gives index value + 1: 2
That's all for now! If you have a correction, best practice, or another common error for me to add, please let me know!
Top comments (3)
Hi Vicky. Nice read. I would highly recommend making the shift to functional programming to iterate over collections. I really got excited about functional programming when I began doing code challenges on codewars.com. When I would submit my answers (written in my old clunky imperative style) I would always see how other solved the same problem. The most simple and elegant answers were ALWAYS written declaratively and I was jealous! So I embraced foreach (now for of in ES6), map, filter, reduce, and all other manners of functional programming and I'm happy with how simple my coding has become.
Vicky, and what is the main point of this article, why working title was "Javascript sucks" ?
This is a list of things I would frequently mix up or forget in JS. I suppose the main point is that JS can be confusing, and to provide a handy reference for myself and anyone else who's come looking. :) Just in case someone's feeling like they're all alone in being confused, you can read this and see you're not the only one!