var myArray=
var i=0
while(i<5){
myArray.push(i)
i++
}
console.log(myArray)
I understand why everything in the function is happening, but why does my console read [0, 1, 2, 3, 4], as in the function it states to increment the variable while under 5. Why is there a 0 in that array?
Your code logs [0, 1, 2, 3, 4] because those are the values of i starting at 0 and continuing until i is no longer smaller than 5. What part of this is different from what you expect?
// Create new array
var myArray = [];
// Initialize iterator to 0
var i = 0
// Loop i = 0 to i = 4
while (i < 5) {
// Push i to end of array
myArray.push(i)
// Increase iterator
i++
}
// Log contents of array
// Contents are [0, 1, 2, 3, 4, 5]
console.log(myArray)
This declares a variable name myArray with a value of an empty array [ ]
Declares the variable i is equals to 0
This is a while loop, and it will run again and again until the condition is right. In this case, the condition is if the variable i smaller the number 5.
Well i was declared with a value of 0, that means the code inside it will run. Then myArray.push(i) fills the variable myArray that have an empty array with the variable i which is currently 0.
Then after that i++ is just a shortcut programmers made because we are lazy that just means i = i + 1. This means the variable i is modified.
So after that the code goes back to the while and check is i smaller than 5. In this case, i has been changed into 1, but its still smaller than 5.
That means the code inside will run again until i is bigger than 5
Finally, this just logs it to your console the variable myArray