Grad Project 1 Solutions: Arrays & Looping

by Keeley Peck

HTML

<h3>Solutions: Arrays &amp; Looping</h3>
<h4>4 Tasks for this Practice Set:</h4>
<ol>
  <li>
    Make an Array of strings and assign it to a variable. You may make the strings a list of anything you like and use a variable name of your choice.</li>
  <li>
    Write a <code>while</code> loop to iterate over each element in your Array and write each one to the console.</li>
  <li>
    Use one of the methods of the Array object to insert a new element to the end of your array. Looking through the methods on the Array reference page at <a href="http://www.w3schools.com/jsref/jsref_obj_array.asp">W3Schools</a> may be helpful.</li>
  <li>
    Using the same conditions as you had in your <code>while</code> loop, write a <code>for</code> loop to iterate over each element in your Array and write each one to the console.</li>
</ol>

JavaScript

"use strict";

// Solution for #1
// Initialize array of vegetables
var veggies = ["Broccoli", "Green Beans", "Carrots", "Celery"];

// Group the output of the array elements in the console 
// for easy differentiation between the While and For loop results
console.group("While loop:");

// Solution for #2
// While loop iterates over each element in the array 
// and outputs the each element to the console
var i = 0;
while (i < veggies.length) {
  console.log(veggies[i]);
  i++;
}

console.groupEnd();

// Solution for #3
// Use the push() method to add a "Peas" element 
// to the end of the veggies array
veggies.push("Peas");

// Group the output of the array elements in the console 
// for easy differentiation between the While and For loop results
console.group("For loop:");

// Solution for #4
// Using the same conditions, the For loop iterates 
// over each element in the array 
// and outputs each element to the console
for (var i = 0; i < veggies.length; i++) {
  console.log(veggies[i]);
}

console.groupEnd();