2018-09-30 23:01:58 +01:00
---
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
challengeType: 1
2019-02-14 12:24:02 -05:00
videoUrl: 'https://scrimba.com/c/c8QbnCM'
2019-07-31 11:32:23 -07:00
forumTopicId: 18220
2021-01-13 03:31:00 +01:00
dashedName: iterate-with-javascript-while-loops
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
You can run the same code multiple times by using a loop.
2020-11-27 19:02:05 +01:00
The first type of loop we will learn is called a `while` loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
2019-05-17 06:20:30 -07:00
```js
var ourArray = [];
var i = 0;
while(i < 5 ) {
ourArray.push(i);
i++;
}
```
2020-11-27 19:02:05 +01:00
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray` .
2019-11-06 13:26:44 -05:00
2018-09-30 23:01:58 +01:00
Let's try getting a while loop to work by pushing values to an array.
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
You should be using a `while` loop for this.
2018-09-30 23:01:58 +01:00
```js
2020-11-27 19:02:05 +01:00
assert(code.match(/while/g));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`myArray` should equal `[5,4,3,2,1,0]` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --after-user-code--
2018-09-30 23:01:58 +01:00
```js
2018-10-20 21:02:47 +03:00
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
// Setup
var myArray = [];
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
// Only change code below this line
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
var myArray = [];
2019-11-06 12:51:59 -05:00
var i = 5;
while(i >= 0) {
2018-09-30 23:01:58 +01:00
myArray.push(i);
2019-11-06 12:51:59 -05:00
i--;
2018-09-30 23:01:58 +01:00
}
```