-2

Need clarification on the below. Answer is "dog" and would like to know why.

Example:

var animals = ["parrot", "cat", "dog"];

console.log(animals[animals.length - 1]);

Console = "dog".

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    Arrays in javascript are 0-indexed. So the last element is at index `length - 1` as the first element is at `1 - 1`. The `i-th` element is indexed at `i - 1`. – ibrahim mahrir Nov 25 '17 at 03:53
  • The length of the array is 3, the indexes are 0, 1, and 2. – Pointy Nov 25 '17 at 03:53

2 Answers2

0

Animal length = 3 as contains 3 elements.
Animals.length - 1 = 2nd element(3-1). Ryt?

If you see in Animal at index 2, the value is dog since array start at 0 index.

 Animal[0] = parrot
 Animal[1]=cat 
 Animal[2]=dog
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31
0

array[index] is a way to access the element of the array .In your case animals in an array & animal.length-1 will be a number.The index starts from 0 so animal.length-1 will point to the element with index 2. In this array dog occupying the second index, so it is consoling dog

var animals = ["parrot", "cat", "dog"];
console.log(animals.length) // 3
var _index = animals.length - 1 // 2
console.log(animals[_index]) // will print element in the index 2
brk
  • 48,835
  • 10
  • 56
  • 78