How it work this code?

var i;
for(i=10; i>=0; i= i-1){
   var s;
   for(s=0; s<i; s = s+1){
    console.log(s)
   }
  console.log(i)

}

Hi,

The code you posted works as following:

var i;

A new variable called β€˜i’ is created. This is used as a counter in the loop later on so we can work out how many times to run the for loop.

for (i=10; i>=0; i= i-1){
}

This sets up the for loop. It gives the i variable a value of 10 (i = 10). The second statement tells JavaScript to keep running the loop when the i variable contains a value that is bigger or equal to 0 (i>=0). The final statement says that after each iteration of the loop, the variable i should be decreased by 1 (i = i - 1).

var s;
for (s = 0; s<i; s = s+1){
    console.log(s);
}

This is another loop (or β€˜nested’) within our first loop. It is run on each iteration of the initial loop. It works in a similar way to the first loop but note the differences in the second and third expression. s < i tells JavaScript to keep running the loop while the β€˜s’ variable is less than the current β€˜i’ value. s = s + 1 says for each time the nested loop is run, add 1 to the β€˜s’ variable at the end.

console.log()

These are used to output the results.

Hope that helps!

1 Like

whats are first console.log running this code i or s ?

The first console.log which will be executed is console.log(s); the one inside the inner loop. @bcoding21 gives a very good explanation of this.

1 Like