JavaScript For Cats

Loops

Now that we have some basic skills under our belt (Author's note: do cats even wear belts?) we can start being lazy. What?! Yes, that's right: programming is about being lazy. Larry Wall, inventor of the Perl programming language, called laziness the most important virtue ⇗ of a good programmer. If computers didn't exist you would have to do all sorts of tedious tasks by hand, but if you learn to program you can lay in the sun all day while a computer somewhere runs your programs for you. It is a glorious lifestyle filled with relaxation!

Loops are one of the most important ways to harness the power of a computer. Remember Underscore.js from earlier? Make sure you have it loaded in the page (remember: you can just hit the up arrow on your keyboard a few times and then hit Enter to load it in again if you need to) and try copy/pasting this into your console:

function logANumber(someNumber) {
  console.log(someNumber)
}
_.times(10, logANumber)

This code uses the times ⇗ method of Underscore which takes in 1 number and 1 function and then starts from 0 and for 10 steps counts up by 1, calling the function with the number each step of the way.

Console

If we were to manually write out what times is doing in the above code it would look like this:

logANumber(0)
logANumber(1)
logANumber(2)
logANumber(3)
logANumber(4)
logANumber(5)
logANumber(6)
logANumber(7)
logANumber(8)
logANumber(9)

But cats refuse to do unnecessary manual work like this so we must always ask ourselves, "am I doing this in the laziest way possible?".

So why is this called looping? Think of it like this: If we were to write out a list of 10 numbers (from 0 to 9) using a JavaScript Array it would look like this:

var zeroThroughTen = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

What times really does is visit each number and repeat a task: in the example above the task was to call the logANumber function with the current number. Repeating tasks in this way is referred to as looping over the Array.