Loops
1. Iterate with JavaScript While Loops
The first type of loop we will learn is called a while loop because it runs “while” a specified condition is true and stops once that condition is no longer true.
// Setup
var myArray = [];
var i = 5;
while (i >=0){
myArray.push(i);
i--;
}
2. Iterate with JavaScript For Loops
// Setup
var myArray = [];
for (var i = 1; i < 6; i++){
myArray.push(i);
}
3. Iterate Through an Array with a For Loop
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
var total = 0;
for (var i= 0; i< myArr.length; i++){
total += myArr[i];
}
4. Nesting For Loops
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product *= arr[i][j];
}
}
5. Iterate with JavaScript Do…While Loops
- Essentially, a do…while loop ensures that the code inside the loop will run at least once
// Change the while loop in the code to a do...while loop so the loop will push only the number 10 to myArray, and i will be equal to 11 when your code has finished running.
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i<5);
6. Replace Loops using Recursion
The recursive version of multiply breaks down like this. In the base case, where n <= 0, it returns 1. For larger values of n, it calls itself, but with n - 1. That function call is evaluated in the same way, calling multiply again until n <= 0. At this point, all the functions can return and the original multiply returns the answer.
Note: Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
// Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
];
function lookUpProfile(name, prop){
// Only change code below this line
for (var i =0; i <contacts.length; i++){
if (contacts[i].firstName == name){
for (var j = 0; j < contacts[i].length; j++){
if (j == prop){
return contacts[i][prop]
} else {
return "No such property"
}
}
} else {
return "No such contact"
}
// Only change code above this line
}c
}
lookUpProfile("Akira", "likes");