2018-10-10 18:03:03 -04:00
---
id: 5675e877dbd60be8ad28edc6
2021-02-06 04:42:36 +00:00
title: Iterate Through an Array with a For Loop
2018-10-10 18:03:03 -04:00
challengeType: 1
2020-04-29 18:29:13 +08:00
videoUrl: 'https://scrimba.com/c/caeR3HB'
forumTopicId: 18216
2021-01-13 03:31:00 +01:00
dashedName: iterate-through-an-array-with-a-for-loop
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2021-02-06 04:42:36 +00:00
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
2020-04-29 18:29:13 +08:00
```js
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length ; i + + ) {
console.log(arr[i]);
}
```
2021-02-06 04:42:36 +00:00
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1` . Our condition for this loop is `i < arr.length` , which stops the loop when `i` is equal to `length` . In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length` and outputs `6` to the console.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Declare and initialize a variable `total` to `0` . Use a `for` loop to add the value of each element of the `myArr` array to `total` .
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`total` should be declared and initialized to 0.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
2021-02-06 04:42:36 +00:00
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
`total` should equal 20.
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(total === 20);
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
You should use a `for` loop to iterate through `myArr` .
2018-10-10 18:03:03 -04:00
```js
2021-02-06 04:42:36 +00:00
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
2020-12-16 00:37:30 -07:00
```
2020-04-29 18:29:13 +08:00
2021-02-06 04:42:36 +00:00
You should not attempt to directly assign the value 20 to `total` .
2020-04-29 18:29:13 +08:00
2020-12-16 00:37:30 -07:00
```js
2021-02-06 04:42:36 +00:00
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
2018-10-10 18:03:03 -04:00
```
2020-04-29 18:29:13 +08:00
2021-01-13 03:31:00 +01:00
# --seed--
## --after-user-code--
```js
(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
```
## --seed-contents--
```js
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
```
2020-12-16 00:37:30 -07:00
# --solutions--
2021-01-13 03:31:00 +01:00
```js
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length ; i + + ) {
total += myArr[i];
}
```