JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a for Loop

Why doesn't this work???

for ( ) { console.log(4, 156) }

script.js
for () {console.log(4))}

1 Answer

Tabatha Trahan
Tabatha Trahan
17,690 Points

The for loop needs a few pieces of information in order to run: it needs an initial value to start with, then a condition to check to see if it should continue on with the body of the loop, then it needs the control variable to change by either increasing or decreasing in value. The challenge is asking to print the numbers 4 up to 156, so you would start your loop out like this:

for(var i = 4; i <= 156; i += 1){
  console.log(i);
}

the var i = 4 is the initialization of your control variable, the i <= 156 is the condition statement that is checked before the body of the loop is executed, and i += 1 is where you increment the control variable. If you don't do this part, you can end up with an infinite loop. The console.log(i) is the statement within the body of the loop to execute as long as the condition is met. Once the value of i is greater than 156, you will jump out of your loop.

Thanks man