2018-09-30 22:01:58 +00:00
---
id: 56105e7b514f539506016a5e
title: Count Backwards With a For Loop
challengeType: 1
2019-02-14 17:24:02 +00:00
videoUrl: 'https://scrimba.com/c/c2R6BHa'
2019-07-31 18:32:23 +00:00
forumTopicId: 16808
2021-01-13 02:31:00 +00:00
dashedName: count-backwards-with-a-for-loop
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
2018-09-30 22:01:58 +00:00
A for loop can also count backwards, so long as we can define the right conditions.
2020-11-27 18:02:05 +00:00
2021-03-03 00:12:12 +00:00
In order to decrement by two each iteration, we'll need to change our initialization, condition, and final expression.
2020-11-27 18:02:05 +00:00
We'll start at `i = 10` and loop while `i > 0` . We'll decrement `i` by 2 each loop with `i -= 2` .
2019-05-17 13:20:30 +00:00
```js
var ourArray = [];
2020-03-25 15:07:13 +00:00
for (var i = 10; i > 0; i -= 2) {
2019-05-17 13:20:30 +00:00
ourArray.push(i);
}
```
2021-03-25 22:18:51 +00:00
`ourArray` will now contain `[10,8,6,4,2]` . Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --instructions--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
You should be using a `for` loop for this.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
You should be using the array method `push` .
2018-09-30 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert(code.match(/myArray.push/));
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`myArray` should equal `[9,7,5,3,1]` .
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-09-30 22:01:58 +00:00
```js
2018-10-20 18:02:47 +00:00
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
// Setup
var myArray = [];
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
// Only change code below this line
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```js
var myArray = [];
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```