Arrays, Objects, and Loops

30.05.2016 |

Episode #7 of the course A quick introduction to JavaScript by Rich Armstrong

 

Start counting to 1000. It’ll take you a long time, right? Try to run this in your console:

for (var i=0; i<1000; i++) {
 console.log(i)
}

7.1 An quick introduction to JavaScript

Fast, huh? This is a typical for loop. We’re setting up a variable called i because it’s short and just applies to the code between {}. We’re then saying that as long as i is smaller than 1000, run the code between {}. And then what the i++ means is that after the code runs, add 1 to i and then reevaluate. As long as it meets the conditions, the code will run. Eventually, i will not be smaller than 1000, and at that point, the code will move onto the line after the for loop. Inside a loop, you can put more loops, define variables and functions, write if-else statements, and do anything you want, really. If you want to exit the loop before it exits naturally, you can call break;. Here’s another example:

function likesFood (food, foodList) {
 var match = false;
 for (var i=0; i<foodList.length; i++) {
   if (food == foodList[i]) {
     match = true;
     break;
   }
 }


 if (match) {
   return 'Yeah, she likes ' + food;
 } else {
   return 'Nope, she does not like ' + food;
 }
}

var herListOfFoods = ['pizza', 'pasta', 'lobster', 'snails', 'cured ham'];
console.log(likesFood('snails', herListOfFoods));
console.log(likesFood('frogs', herListOfFoods));

Computers are pretty quick at counting and combing objects and iterating over arrays—actually, they’re super quick! There are a few different kinds of loops, so I’ll show you one more type here that is especially good for looping through objects:

// a for in loop, with an object 
var someObj = {
 firstName: 'Bob',
 lastName: 'McDonald',
 age: 92,
 hobbies: ['pipe smoking', 'horse riding', 'wood chopping'],
 canShootARifle: true,
 numberOfKids: 5
};
for (item in someObj) {
 console.log('someObj\'s '+item + ': ' + someObj[item]);
}

// a for in loop, with an array
var citiesLiveIn = ['Joburg', 'Durban', 'Amsterdam'];
for (i in citiesLiveIn) {
 var num = parseInt(i)+1;
 console.log('city: ' + num + ': ' + citiesLiveIn[i]);
}

Now try to write your own loops. Try changing values. Try creating new objects. Try looping inside of a loop (like loop inception). And maybe see what number the computer can count up to!

Remember: Download Google Chrome for Desktop and Sublime Text 3 to make the most of these lessons. And remember to open up your JavaScript Console: Alt+Cmd+J (OS X) or Alt+Ctrl+J (Windows).

 

Recommended book

“JavaScript: The Ultimate Beginner’s Guide!” by Andrew Johansen

 

Share with friends