Loops with If

When an array contains elements with different types, you'll need to use if statements to perform some type checking. Here is the code to loop through an array and add only the number elements:

function numberAdder (stuff) {
  var result = 0;
  for (var i = 0; i < stuff.length; i++) {
    var element = stuff[i];
    if (typeof(element) == "number") {
      result += element;
    }
  }
  return(result);
}

var weird = [1, 40, "bob", [], false, 89];
var r = numberAdder(weird);
console.log(r); // 130

The numberAdder() iterates through all the elements in the weird array and adds the element to the running total if it is a number.

Now let's write a function to concatenate all the elements in an array that begin with the letter "b".

function stringConcatenator (array) {
  var result = "";
  for (var i = 0; i < array.length; i++) {
    var element = array[i];
    if (element[0] == "b") {
      result += element + " ";
    }
  }
  return(result);
}

var heaven = [34, [], "bodacious", "barbecues", "begin", "whatever", "by", "battering", true, "bacon"];
var r = stringConcatenator(heaven);
console.log(r); // "bodacious barbecues begin by battering bacon"
Question Click to View Answer

What does the following code print to the console?

function joinIfString (array) {
  var result = "";
  for (var i = 0; i < array.length; i++) {
    if (typeof(array[i]) === "string") {
      result += array[i];
    }
  }
  return(result);
}

var planet = ["earth", "fire", 34, undefined, "wind", [], "water"]
var r = joinIfString(planet);
console.log(r);

earthfirewindwater

The joinIfString() function joins every string in the planet array.

What does the following code print to the console?

function logEvenNumbers (n) {
  var i = 0;
  while (i < n) {
    if (i % 2 === 0) {
      console.log(i + " is an even number");
    }
    i++;
  }
}
logEvenNumbers(5);
0 is an even number
2 is an even number
4 is an even number

The logEvenNumbers() function iterates through all numbers from 0 to n and prints if the number is even or not.

<-- Previous (Modulus Operator) Next (Foreach Functions) -->