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".
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".
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
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