Variable as an Index

Allright people, here I am asking for help once again! Just can’t understand one thing and it’s driving me crazy, I want to get the last number (the one at the last index) from an array of numbers.
I want to use a variable, called test as an index, but I keep getting “undefined”…what am I doing wrong?

Output from console.log(test) = 3 so this works
Output from console.log(arr[test]) = undefined

let test = 0;
test = arr.length;


  **Your browser information:**

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

Challenge: Where do I Belong

Link to the challenge:

Remember that arrays are zero indexed. The first element is 0 the second 1 and so on.

This means the length as an index will be outside the array.

//index   0    1    2
array = ['a', 'b', 'c'];
array.length == 3;

// 3 is outside the array
1 Like

Side note - test isn’t a great variable name.

Lets look at what’s happening:

const myArr = [5, 42, 9];
const myArrLength = myArr.length;

for (let i = 0; i <= myArrLength; i++) {
  console.log("i:", i);
  console.log("myArr[i]:", myArr[i]);
1 Like

Damn…damn, I knew it was something simple yet I was too focused too see it…Ahah, thanks!

1 Like

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