educative.io

Understanding code

I would like some explanation on this part of the code.
I know what the code is doing but I do not know how it is doing it.
I know n is initialising while false and checking it again but how is it initialising and how is it checking the count.

let n = 1;
let check = false;
for (let i = 1; check == false; i++) {
if (i % 2 === 1) {
console.log(${i} is odd);
if(n == 10)
check = true;
n++;
}
}

Hi Mahmoud,

Thanks for writing to us.
The variable n is initially being declared and set to a value of 1 as specified in the code
let n = 1;

We check the value of n by checking the value of the variable check. So in the for loop, there is a condition that keep incrementing the value of i while check==false. As soon as check is true, the loop ends. check is updated to true when n is equal to 10.

The line n++ increments n’s value at every iteration until it’s value reaches 10; At that point check = true and the loop ends. To see what is the value of check according to the value of n we use the following condition:
if(n == 10) check = true;

So when n==true, set check=true

Hope this answers your query.
Happy learning!

Kind regards,
Mishaal
Developer Advocate | Educative

1 Like