For Loops - Fundamentals.
What is going on when we get in a for loop?
. Initial Expression — this is simply a place for you to initialize any JavaScript expression (an expression is a bit of JavaScript code that evaluates to a single value). Most often, it’s used to declare a variable, in this case i, that will be used as a counter for how many times the loop iterates. You should definitely follow this pattern until you’re comfortable enough to try a more complex expression.
Finally, once you’ve declared your loop conditions, you can insert the code that you want to be repeated inside of the curly braces {}. Again this code will be executed until your condition (#2 above) evaluates to false.
Challenge: For Loops and Arrays
const synonyms = ['fantastic', 'wonderful', 'great']; const greetings = [];
for (let i = 0; i < synonyms.length; i++) {
greetings.push('Have a ' + synonyms[i] + ' day!');
}
for (let i = 0; i < greetings.length; i++) {
console.log(greetings[i]);
}How do you calculate array elements?
You are given an array of five numbers called increaseByTwo. Use a for loop to iterate through the array and increase each number by two.
const increaseByTwo = [1, 2, 3, 4, 5];
const increaseByTwo = [1, 2, 3, 4, 5];
for (let i = 0; i < increaseByTwo.length; i++) {
increaseByTwo[i] = increaseByTwo[i] + 2;
}console.log(increaseByTwo);
[3, 4, 5, 6, 7]
Use a loop to iterate through the numbers 1 through 16. Push each number into fb, but push the string “fizz” in place of numbers divisible by 3, “buzz” in place of numbers divisible by 5, and “fizzbuzz” in place of numbers divisible by both 3 and 5.
Log fb to the console to see the output.
const fb = [];
const fb = [];
for (let i = 1; i < 17; i++) {
if (i % 3 === 0 && i % 5 === 0) {
fb.push("fizzbuzz");
} else if (i % 3 === 0) {
fb.push("fizz");
} else if (i % 5 === 0) {
fb.push("buzz");
} else {
fb.push(i);
}
}console.log(fb);
[1, 2, ‘fizz’, 4, ‘buzz’, ‘fizz’, 7, 8, ‘fizz’, ‘buzz’, 11, ‘fizz’, 13, 14, ‘fizzbuzz’, 16]
How do we return/access the last letter of a string without numerically placing a value/index in a bracket?
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.