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'
2018-09-30 23:01:58 +01:00
---
## Description
<section id='description'>
You can run the same code multiple times by using a loop.
2019-03-19 15:04:03 +05:30
The first type of loop we will learn is called a <code>while</code> 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++;
}
```
2018-09-30 23:01:58 +01:00
Let's try getting a while loop to work by pushing values to an array.
</section>
## Instructions
<section id='instructions'>
Push the numbers 0 through 4 to <code>myArray</code> using a <code>while</code> loop.
</section>
## Tests
<section id='tests'>
```yml
2018-10-04 14:37:37 +01:00
tests:
- text: You should be using a <code>while</code> loop for this.
2019-07-13 00:07:53 -07:00
testString: assert(code.match(/while/g));
2018-10-20 21:02:47 +03:00
- text: <code>myArray</code> should equal <code>[0,1,2,3,4]</code>.
2019-07-13 00:07:53 -07:00
testString: assert.deepEqual(myArray, [0,1,2,3,4]);
2018-09-30 23:01:58 +01:00
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myArray = [];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
2018-10-20 21:02:47 +03:00
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
2018-09-30 23:01:58 +01:00
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myArray = [];
var i = 0;
while(i < 5) {
myArray.push(i);
i++;
}
```
</section>