JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  • Completed Code
  • Explanation
  1. 05-Arrays
  2. Solutions
  3. First and Last

Last Element

Completed Code

var arr=[ 'We', 'love', 'learning', 'JavaScript!','It', 'is', 'a', 'fantastic', 'language' ];

last = function(array) {
    return array[array.length - 1];
};

console.log(last(arr));

Explanation

The code for this challenge is very similar to the previous one, however there is one small change. Rather than using an index, we use the length property of the array. Length is NOT zero-based, in order to get the last element we have to subtract one to call the proper index. If we didn't subtract one, our output would be undefined. This array does not have an element with an index of six.

PreviousFirst ElementNextMost Frequent

Last updated 7 years ago