Questions about array

Is there a way to have the code print just the last item in an array?

1 Like

Sure! You can do that like this:

console.log(array[array.length - 1])

array representing the name of the array you want to print.
array.length - 1 is the number of items in the array, minus 1.

For example, if the array animals had 3 items in it:

let animals = ['dogs', 'cats', 'whales']

'dogs' is at animals[0], 'cats' is at animals[1], and 'whales' is at animals[2].

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

This is the same as printing out animals[2], because animals.length is 3.

Hope that helps! Let me know if you have any questions.

i like the codes idsds

1 Like