for
loops, ones that do things for
each time with a predefined count/set, and while
loops, which run while
a condition is true
.for
loopsIn JavaScript, the syntax of a for
loop is as follows:
for (var i=0; i<20; i=i+1) {// Things to do each time.}
Inside the round brackets, there are 3 pieces of code, separated by semicolons (;).
var i=0
is the first piece, and is the setup code. It declares a variable (named i
) and sets it to 0 to begin.i<20
is the second piece, and is the "check" (stop) condition. If the condtion is is true
, the loop will continue. If false
, it stops.i=i+1
is the third piece, and is the "cycle" code. It runs after every "cycle" (iteration) of the loop.
In this case, we're adding 1
to i
, which can also be represented by i++
or ++i
.In general, you can read it as:
for (<initial condition/setup>; <check/stop condition>; <run after each cycle>) {// Code}
Any or all of these 3 pieces can be omitted, but you must keep the semicolons.
This loop will run forever:
for (var i=0; i<5; ) {// i never gets incremented, so every time the loop runs, it will remain 0.}
Similarly, if you leave out the stop condition, it will always run forever.
The break
keyword can be used like any other line of code, but instead it immediately stops the loop.
The continue
keyword is like break
, but instead of stopping the loop, it just ends the current cycle (iteration), and goes to the next iteration.
There also exists the ability to use a for
loop "for each item in this list", but that isn't needed here. It's known as a "for each" loop.
while
loopsIn JavaScript, the syntax of a while
loop is as follows:
while (<condition>) {// Code}
It runs while the condition is true
. It's like omitting both the setup and after-each-iteration pieces from the for
loop.
This is much simpler, but you have to remember to do setup beforehand, and any variable changes must happen inside the loop.
You are much more likely to make a mistake with a while loop, and end up with an infinite loop - one that runs forever. Just close the window though, and it will stop. Worst case - you reboot your computer. (It's only a problem when you have infinite loops that keep robots driving forever, through walls and then they run away.)
for
and while
). For example:var i=0;while (i==0) {i=27; // i is no longer zeroconsole.log("some message"); // this will still run!console.log("this will run the first time before i is checked again");// before looping again, it checks i, and sees it's not zero, and exits the loop.}
My First Loop
The first time this loop runs, what is the value of i
?
Q1: Write down the value of i
at the start of each iteration (including the first) in the loop, in order of execution. (This is Q1 on the assignment.)
My First Loop
Q2: Write down each value of i
and j
for each iteration of the loop, in the order of execution.
Hint: Watch out for the break
statement!
Just like if
statements, loops can be nested inside each other. For instance:
for (var i=0; i<10; ++i) {for (var j=0; j<10; ++j) {var num = i.toString() + j.toString();}}
This is a very convoluted way of counting to 100. For every iteration in the outside loop (with the variable i
), the inside loop (with variable j
) will complete a full set of (10) iterations.
Obviously, we must use different variable names or the values will overwrite each other. When we create var num
, we take i
and convert it to a string, then do the same for j
, and add the two together.
Because we are adding strings, the characters within are simply combined, or concatenated, so no maths is actually performed. This script will make the strinng "00", then "01", "02", up to "09" for all the values of j
(while i
remains 0
). Then, i
becomes 1
, and the strings "10", "11", "12" through "19" are generated, and so on for increasing values of i
and j
up to "99" before exiting.
Code appears to be from https://web.archive.org/web/20180327090707/https://www.mindstick.com/blog/390/using-javascript-nested-loops
Nested loops in JavaScript
Q3: Write down the values of i
and j
, together, for each iteration of the inner loop, in order of execution.
When using a loop, you should take care to pick the right one, although both kinds are often interchangeable (in JavaScript, at least).
A for
loop has places available for setup and end-of-iteration code. It's designed to run a set number of times, whether that's a variable with that number, or you enter the specific number yourself (e.g. 15
).
A while
loop is used when you want to run until something changes, e.g. wait until the light goes green, then drive. You must write setup code outside the loop, and any changes to variables must be done inside the loop. If you forget, you might end up with that infinite loop (don't stay waiting at a green light)!
Q4: Change each of the for
loops into while
loops for the previous questions.
(Not part of assignment): Which loop is better for each of the questions?