Wednesday, May 19, 2021

Javascript Practice 51: JS Hero - Get array elements

 
Question: 

Write a function getFirstElement that takes an array and returns the first element of the array.

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




Answer: 

function getFirstElement (array) { 

let firstEl = array[0];
return firstEl

}





> declare a function getFirstElement 
> it has 1 parameter array
> we declare a variable firstEl 
> we initialize it with the first element of the array
> we access the first element of the array by entering '0' in between the square brackets
> index in an array begins with '0' 
> we return the firstEl variable 

No comments:

Post a Comment