Basic JavaScript - Iterate Through an Array with a For Loop

Tell us what’s happening:

Why in the examples, did we not explicitly assign i?
My code states that i is not defined. What does this mean?

Your code so far

// Setup
const myArr = [2, 3, 4, 5, 6];
let total=0;

for (i = 0; i < myArr.length; i++){
  total += myArr[i];
}
// Only change code below this line

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36

Challenge Information:

Basic JavaScript - Iterate Through an Array with a For Loop

you used i but not defined it before

1 Like

Generally in for loops you want to declare the variable using a keyword let or var.

Reason for this is when you declare a variable that doesn’t exist yet using somehting like i = 0 without var/let it will create a global variable no matter where you are declaring it which is usually unintended. Normally variables are scoped to the functions/blocks they are in, for example:

function coolFunc() {
  let myNum = 20
  return myNum;
}
coolFunc() // 20
myNum //  myNum is not defined

When you don’t use a keyword, it messes this scoping up though:

function coolFunc() {
  myNum = 20
  return myNum;
}
coolFunc() // 20
myNum //  20 - this is bad, we don't want myNum to exist globally

Thanks! Forgot to put let before i.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.