TunaK2
September 13, 2022, 9:56pm
1
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
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
(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”.
system
Closed
March 15, 2023, 10:12am
5
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.