Search

Return the First Element in an Array in JavaScript

  • Share this:

To return the first element in an array in JavaScript, you can use the following approach:

Step 1: Define a function that takes an argument `arr`. This argument will be the array from which you want to return the first element:

function firstElement(arr) {
  // code to return the first element in the array
}

Step 2: Inside the function, use the following code to return the first element in the array:

function firstElement(arr) {
  return arr[0];
}

Step 3: Here is the complete code:

function firstElement(arr) {
  return arr[0];
}

var result = firstElement([1, 2, 3, 4, 5]);
console.log(result); // Output: 1

You can also use the following shortened version of the function:

const firstElement = arr => arr[0];

var result = firstElement([1, 2, 3, 4, 5]);
console.log(result); // Output: 1

Note that this function will return `undefined` if the array is empty. You can add a check for an empty array at the beginning of the function to handle this case:

function firstElement(arr) {
  if (arr.length == 0) return "The array is empty";
  return arr[0];
}

var result = firstElement([]);
console.log(result); // Output: "The array is empty"

 

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.