BDI Logo

Introduction to JavaScript

Class 3

Loops

Lego stormtrooper inside key ring

Photo credit: Steve Pires cc

While loops

While will repeat the same code over and over until some condition is met.

var bottlesOfBeer = 99;
  while (bottlesOfBeer >= 1) {
    console.log (bottlesOfBeer + ' bottles of beer on the wall');
    bottlesOfBeer = bottlesOfBeer - 9;
  }
  

Infinite Loops

Make sure something changes in the loop, or your loop will go on forever...

Spiral that goes on toward infinity

Photo credit: Samuel John cc

For loops

For loops are very similar, but you declare a counter in the statement.

//will count 1 to 10
  for (var i = 1; i <= 10; i++) {
    console.log (i);
  }
  

Loops and logic

You can add other statements or logical operators inside the loops.

//Count from 1 to 50
  for (var i = 1; i <= 50; i++) {
    console.log (i);
    //Says 'Buzz' after multiples of three
    if (i % 3 == 0) {
      console.log (' Buzz');
    }
    //Says 'Bang' after multiples of five
    if (i % 5 == 0) {
      console.log (' Bang');
    }
  }
  

Break

To exit a loop, use the break statement.

//Count from 100 to 200
  for (var i = 100; i <= 200; i++) {
    console.log('Testing ' + i);
    //Stop at the first multiple of 7
    if (i % 7 == 0) {
      console.log('Found it! ' + i);
      break;
    }
  }
  

Let's Develop It

Write a loop that gives you the 9's times table,
from 9 x 1 = 9 to 9 x 12 = 108.

Finish early? Try using a loop inside a loop to write all the times tables, from 1 to 12.

Arrays

Group of kittens

Photo credit: Jesus Solana cc

Arrays

Arrays are ordered lists of values.

var arrayName = [element0, element1, ...];
  

You can put different types of data into an array.

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
  'Blue', 'Indigo', 'Violet'];
  var lotteryNumbers = [33, 72, 64, 18, 17, 85];
  var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
  

Array Length

The length property tells you how many things are in an array

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
  'Blue', 'Indigo', 'Violet'];
  console.log(rainbowColors.length);
  

Using Arrays

You can access items with "bracket notation" by using the position of the object you want. Programmers start counting at zero.

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
  'Blue', 'Indigo', 'Violet'];
  var firstColor = rainbowColors[0];
  var lastColor = rainbowColors[6];
  

Changing arrays

You can use bracket notation to change an item in an array

var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
  myFavoriteThings[0] = 'Asparagus';
  

Expanding arrays

Arrays do not have a fixed length. You can use "push" to add something to an array.

var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
  myFavoriteThings.push('Dancing');
  

Let's Develop It

Create an array of your favorite foods. Echo a few values onto your screen.

Arrays + loops = BFF

Couple holding hands

Photo credit: John cc

Iterating through arrays

Use a for loop to easily process each item in an array.

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
    'Blue', 'Indigo', 'Violet'];
  for (var i = 0; i < rainbowColors.length; i++) {
    console.log(rainbowColors[i]);
  }
  

Let's Develop It

Use a loop to make a list of all your favorite foods.

Objects

Collection of matches

Photo credit: Jirí Volejník cc

Objects

Objects let us store a collection of properties.

var objectName={
  propertyName: propertyValue,
  propertyName: propertyValue,
  ...
};
var aboutMe={
  hometown: 'Atlanta, GA',
  hair: 'Auburn',
  likes: ['knitting', 'code'],
  birthday: {month: 10, day: 17}
};

Accessing Objects

You can retrieve values using "dot notation"

var aboutMe={
  hometown: 'Atlanta, GA',
  hair: 'Auburn'
};
var myHometown=aboutMe.hometown;

Or using "bracket notation" (like arrays)

var myHair=aboutMe['hair'];

Changing Objects

You can use dot or bracket notation to change properties

var aboutMe={
  hometown: 'Atlanta, GA',
  hair: 'Auburn'
};
aboutMe.hair='blue';

Add new properties

aboutMe.gender='female';

Or delete them

delete aboutMe.gender;

Arrays of Objects

Because arrays can hold any data type, they can also hold objects

var myCats=[
  {name: 'Lizzie',  age: 18},
  {name: 'Daemon',  age: 1}
];

for (var i=0; i < myCats.length; i++) {
  var myCat=myCats[i];
  console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}

Arrays of Objects

Just like other data types, objects can be passed into functions:

var lizzieTheCat={
  age: 18,
  furColor: 'grey',
  likes: ['catnip', 'milk'],
  birthday: {month: 7, day: 17, year: 1996}
}

function describeCat(cat) {
  console.log('This cat is ' + cat.age + ' years old with '
  + cat.furColor + ' fur.');
}

describeCat(lizzieTheCat);

Let's Develop It

Create an object to hold information on your favorite recipe. It should have properties for recipeTitle (a string), servings (a number), and ingredients (an array of strings).

Try displaying some information about your recipe.

Bonus: Create a loop to list all the ingredients.

Object methods

Objects can also hold functions.

var lizzieTheCat={
  age: 18,
  furColor: 'grey',
  meow: function() {
    console.log('meowww');
  },
  eat: function(food) {
  console.log('Yum, I love ' + food);
  },
};

Call object methods using dot notation:

lizzieTheCat.meow();
lizzieTheCat.eat('brown mushy stuff');

Let's Develop It

Go back to your recipe object. Add a function called letsEat that says "I'm hungry! Let's eat."

Call your new method.

Built-in methods

JS provides several built-in objects:

You did it!

Fireworks

Photo credit: Mark W. cc

Resources

Questions?