Wednesday, May 19, 2021

Javascript Practice 53: JS Hero - Array: length

 
Question: 

Write a function getLastElement that takes an array and returns the last element of the array.

Example: getLastElement([1, 2]) should return 2.




Answer: 

function getLastElement (anArray) {

  let lastIndex = anArray.length - 1;
  return anArray[lastIndex];

}




> we learn how to access the last element of an array 
> we use the length property 
> this property will return the number of elements in the array 
> subtracting 1 from the length of an array gives the index of the last element of that array
> this index can be used to access the last element of that array 
> we declare a function getLastElement
> it has 1 parameter anArray
> we declare a variable lastIndex
> we initialize it with a value, which will be the index of the last element of the array
> we then return the last element like this: anArray [lastIndex]

No comments:

Post a Comment