2

I was reading Eloquent JS and came across this code which didn't make sense to me. I wasn't able to understand it as it was explained and was hoping someone could explain to me why the second console.log evaluates to the value it does.

Here's the code:

var listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[1]);
// → 3
console.log(listOfNumbers[1 - 1]);
// → 2

Any ideas?

1
  • 2
    listOfNumbers[1 - 1] is the same as listOfNumbers[0] Commented Aug 28, 2015 at 14:51

4 Answers 4

5

2 is the first number in the zero-indexed array

listOfNumbers[1 - 1] = listOfNumbers[0] = 2
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I was looking for. Thanks Curt!
@MaxZoom Definitely will do. I'm waiting for the required 12 minutes to pass.
1

listNumber is an array containing 2, 3, 5, 7, 11

listNumber[0] is 2

listNumber[1] is 3

listNumber[2] is 5 listNumber[3] is 7 listNumber[4] is 11

listNumber[1-1] => listNumber[0] => 2

console.log(listNumber[0]); //will print 2 at console

Comments

0

arrays are 0 indexed. so list[0] = 2, list[1] = 3

Comments

0

[0] is the first element in an array. [1] is the second. Array indexes start with 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.