Last Array Element

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript function that helps us find the last element of an array. We will learn how to check if an array is valid and has a length property, and how to use the length property to compute the index of the last element. We will also learn how to return undefined if the array is empty or invalid.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28463{{"`Last Array Element`"}} javascript/data_types -.-> lab-28463{{"`Last Array Element`"}} javascript/arith_ops -.-> lab-28463{{"`Last Array Element`"}} javascript/comp_ops -.-> lab-28463{{"`Last Array Element`"}} end

How to Get the Last Element of an Array in JavaScript

To get started with coding, open the Terminal/SSH and type node. The following function returns the last element in an array:

const last = (arr) => (arr && arr.length ? arr[arr.length - 1] : undefined);

To use it, you need to provide an array as an argument. The function checks if the array is truthy and has a length property. If both conditions are true, it computes the index of the last element of the array and returns it. Otherwise, it returns undefined.

Here are some examples:

last([1, 2, 3]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined

Summary

Congratulations! You have completed the Last Array Element lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like