Preview

10 - Advanced Loops (For, While, For in)

 1. The following code adds up numbers from 1 to 10, but this would be inefficient as a method for adding 1000 numbers. What could be used instead?

  loops

  modules

  variables

  if statements

 2. In the following code the purpose of i=0 is to ensure that the code never goes above the number 0
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

  FALSE

  TRUE

 3. The i < 5 defines the condition for the loop to run (in this case that the loop must run at least 25 (5 x 5) times.

  TRUE

  FALSE

 4. The i++ increases or increments the value of the variable i each time the code block in the loop has been executed.

  FALSE

  TRUE

 5. The for/in statement loops through the properties of an object.. What is the output here?
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>The for/in statement loops through the properties of an object.</p>

<p id="demo"></p>

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
  txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

  John Doe 25

  John

  25

  fname, lname, age

 6. The following while loop iterates as long as n is less than three. Which of the following statements is true?
var n = 0;
var x = 0;
while (n < 3) {
  n++;
  x += n;
}

  All of these options are correct

  After the second pass: n = 2 and x = 3

  After the first pass: n = 1 and x = 1

  After the third pass: n = 3 and x = 6

 7. What is true of this while loop?
while (true) {
  console.log('Hello, world!');
}

  It will simply output the word 'true' to the screen, as there are no numeric start or stop conditions

  It is infinite because the condition never becomes false

  It will not loop at all as there is no start or stop condition

  It will loop just once, as there are no explicit conditions

 8. Nothing is being displayed on the screen. Changing "var i=10;" to "var i=11", would fix the issue
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var text = "";
var i = 10;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

  TRUE

  FALSE

 9. The following example iterates through the elements in an array until it finds the index of an element whose value is theValue - it then breaks
for (var i = 0; i < a.length; i++) {
  if (a[i] == theValue) {
    break;
  }
}

  FALSE

  TRUE

 10. The __________statement can be used to restart a while, do-while, for, or label statement.
var i = 0;
var n = 0;
while (i < 5) {
  i++;
  if (i == 3) {
    continue;
  }
  n += i;
  console.log(n);
}
//1,3,7,12

  while

  log

  console

  continue