can anyone tell me why it has printed 3 in the last one please
let listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[2]);
// → 5
console.log(listOfNumbers[0]);
// → 2
console.log(listOfNumbers[2 - 1]);
// → 3
can anyone tell me why it has printed 3 in the last one please
let listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[2]);
// → 5
console.log(listOfNumbers[0]);
// → 2
console.log(listOfNumbers[2 - 1]);
// → 3
Why do you think 3 is printed? Did you expect a different output? If so, why?
asking yourself these question, this way of thinking is rather important for a programmer.
It looks like print a range from 2 to 1 but it doesn’t make sense.
Why would it print a range?
The print gives the value of 3
, which is the second element (index 1) of the list. So 2 - 1
is a simple subtraction.
I was subtracting the values and not the position. That’s why I didn’t consider this one. Thanks anyway