> For the complete documentation index, see [llms.txt](https://raffycastlee.gitbook.io/marcyannotes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://raffycastlee.gitbook.io/marcyannotes/codechallenge-curriculum/unit-2/20241015.md).

# CC-07: Array Iteration

with Carmen Salas • 2024/10/15

[slides](https://docs.google.com/presentation/d/1to0IN-CcF4NJpzdq4tSgWgBJUbq6EYstq_iJqCYbonw/edit#slide=id.g287c4ecafef_0_150)

* [Arrays](#arrays)
* [Code Challenge](#code-challenge)

## Arrays

slides review\...

`for...of` syntax when looping through an iterable's **values**:

```js
for (let item of collection) {
    // iterating through values,
    // DOES NOT SKIP over undefined/skipped indices
}
```

`for...in` syntax when looping through an iterable's **enumerables**:

```js
for (let index in collection) {
    // iterating through indices,
    // SKIPS over undefined/skipped indices
}
```

## Code Challenge

1. Declare a function named sumInArray that will calculate the sum of all the elements in an array of numbers. You must solve this without using any built-in array methods and iterating through the array.

```js
const sumInArray = (arr) => {
  let sum = 0;
  for (let val of arr) {
    sum += val;
  }
  return sum;
}

// console.log(sumInArray([2,4,5,7,8])) // returns 26
// console.log(sumInArray([2,2,5,10])) // returns 19
// console.log(sumInArray([2,2,2,2,2])) //returns 10
```

2. Declare a function named averageInArray that will calculate the average of the elements in an array of numbers. You must solve this without using any built-in array methods and iterating through the array.

```js
const averageInArray = (arr) => {
  let sum = 0;
  for (let val of arr) {
    sum += val;
  }
  return sum / arr.length;
}

// console.log(averageInArray([2,4,5,7,8])) // returns 5.2
// console.log(averageInArray([2,2,5,10])) // returns 4.75
// console.log(averageInArray([2,2,2,2,2])) //returns 2
```
