Let’s write a program that prints out the number 0 through 5 to the JavaScript Console. →
//start out with the surrounding html
console.log(0)
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
How can we change this so that we print out a single variable that is incremented after each print. →
// what if we just want to make multiple calls to the following line...
console.log(n);
// what's the missing code to make this count from 0 through 5?
var n = 0;
var increment = 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
Is there a pattern here? →
var n = 0;
var increment = 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
n = n + 1;
console.log(n);
The following two lines were repeated 5 times! →
console.log(n);
n = n + 1;
That’s a bit tedious, right?
Wouldn’t it be great if we could just tell the computer to repeat this block of code for us? →
console.log(n);
n = n + 1;
Some formal definitions:
JavaScript has a couple of structures that allow us to repeat blocks of code!
For now, we’ll use for loops to repeat a block of code a specific number of times. The following code counts from 0 through 5. →
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
Consists of the keyword, for, and three parts, separated by a semicolon, contained in parentheses:
You can use the variable that you declare in the initialization within your for loop!
// initialization
// | condition
// | | afterthought/increment
// | | |
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
// initialization
// | condition
// | | afterthought/increment
// | | |
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
Notice that:
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
How can we change our loop to count from 5 to 10 instead? →
for(var i = 5; i <= 10; i = i + 1) {
console.log(i);
}
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
How can we change our loop to count by 2’s from 0 to 10? →
for(var i = 0; i <= 10; i = i + 2) {
console.log(i);
}
for(var i = 0; i <= 5; i = i + 1) {
console.log(i);
}
How can we change our loop to count backwards from 10 to 0? →
for(var i = 10; i >= 0; i = i - 1) {
console.log(i);
}
Write a program that adds the numbers 1 through 100 together. Try creating a variable outside of the for loop… and change that variable on each iteration. →
var total = 0;
for(var num = 1; num <= 100; num = num + 1) {
total = total + num;
}
console.log(total)
Ask the user for a number… and use a for loop to count from 1 up to that number.
var answer = prompt("Give me a number to count up to");
var end = parseInt(answer);
for(var num = 1; num <= end; num = num + 1) {
console.log(num);
}