Introduction
In this lab, we will explore a JavaScript function that returns the head of an array. The function checks if the input array is valid and returns the first element if it exists, otherwise it returns undefined. Through this lab, you will gain a better understanding of array manipulation in JavaScript and learn how to handle edge cases when working with arrays.
This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 95% positive review rate from learners.
How to Get the First Element of an Array in JavaScript
To get the first element of an array in JavaScript, you can use the head function. Here's how you can use it:
- Open the Terminal/SSH.
- Type
nodeto start practicing coding. - Use the following code to get the head of an array:
const head = (arr) => (arr && arr.length ? arr[0] : undefined);
- Call the
headfunction with an array as its argument to get the first element. If the array is empty or falsy, the function will returnundefined.
Here are some examples:
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined
Summary
Congratulations! You have completed the Head of Array lab. You can practice more labs in LabEx to improve your skills.