You are here: Home / Topics / Return the First Element in an Array in JavaScript

Return the First Element in an Array in JavaScript

Filed under: JavaScript on 2023-08-06 20:50:56

Create a function that takes an array containing only numbers and return the first element.

Examples:

getFirstValue([1, 2, 3]) ➞ 1
getFirstValue([80, 5, 100]) ➞ 80
getFirstValue([-500, 0, 50]) ➞ -500

Notes:

The first element in an array always has an index of 0.

Code:

 

<script>

function getFirstValue(array){

return array[0]; //in array indexing starts with zero.

}

 

var array = [45, 65, 98, 100];

console.log(getFirstValue(array)); //this will print 45 in console.

</script>


About Author:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free. Share your stuff here so that others can get benefitted.