Basic JavaScript - Iterate with JavaScript For Loops

I am trying to create an Array as [1,2,3,4,5]. the problem is why the i == 5 statement doesn’t work for this statement. Isn’t it creating a condition like “until i equals 5”?

const myArray = [];

// Only change code below this line
for(var i = 1; i == 5; i++){
myArray.push(i);
}

console.log(myArray);
1 Like
  • loop expressions evaluated for the first time
  • i is 1
  • condition evaluates to 1 == 5, which is false
  • loop exits because the condition evaluates to false

(Edit: you literally have to change a single character here in the condition, the loop only runs while that returns true)

Edit edit: and if you use equality for the condition rather than less than (which is totally fine, it’s just not is equal you want), can’t be a 5

2 Likes

In your for loop, if you had written i <= 5 instead of i==5, that would be a way to create a condition like “until i equals 5”.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.