* fix: added info and solutions for stubs * fix: made title match main header * fix: removed wrong closing tag Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: added closing tag Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: corrected solution Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: changed verbiage Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: added code tags Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: added solution
1.2 KiB
title
| title |
|---|
| Iterate with JavaScript For Loops |
Iterate with JavaScript For Loops
Hints
Hint 1
for(var i = 0; i < 5; i++) { // There are 3 parts here
There are three parts to for loop. They are separated by semicolons.
-
The initialization:
var i = 0;- This code runs only once at the start of the loop. It's usually used to declare the counter variable (withvar) and initialize the counter (in this case it is set to 0). -
The condition:
i < 5;- The loop will run as long as this istrue. That means that as soon asiis equal to 5, the loop will stop looping. Note that the inside of the loop will never seeias 5 because it will stop before then. If this condition is initiallyfalse, the loop will never execute. -
The increment:
i++- This code is run at the end of each loop. It's usually a simple increment (++operator), but can really be any expression. It is used to move the counter (i) forward (or backwards, or whatever).
Solutions
Solution 1 (Click to Show/Hide)
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
var myArray = [];
for (var i = 1; i < 6; i++) {
myArray.push(i);
}