JavaScript Array Type

Extraction

We now know how to create arrays, but how do we get elements of them? The most straight forward way is to get an element at some index in the array.

It's important to remember that JavaScript arrays are zero-based, meaning the first element is on index zero and the last element is on an index one lower than the length of the array.

The syntax for accessing an array item is simple. The array identifier followed by square brackets with an integer number in-between will get us the element at that index.

const element = identifier[index]

If we specify an index lower than zero or higher than the length of the array minus one, we'll get undefined in return. Unlike many other programming languages JavaScript has decided that it's not a critical error to ask for an element at an index out of bounds.

Code example

const characters = [
"Vin", "Sazed", "Elend", "Lestibournes"
]
const first = characters[0]
console.log(first) // Vin

Destructuring assignment

There are times where we only want the first couple of elements and immediately bind them to constants or variables. Modern JavaScript has built-in support for this where the feature is called a destructuring assignment.

Think about the combination of those words.

  • Destructuring: pull something apart.
  • Assignment: assign the parts to something.

We can extract specific elements using destructuring assignments, and also use the rest operator to assign the rest of the array to another variable as shown in the example below.

Code example: destructuring

const characters = [
"Vin", "Sazed", "Elend", "Lestibournes"
]
const [first, second, ...rest] = characters
console.log(first) // Vin
console.log(second) // Sazed
console.log(rest) // ["Elend", "Lestibournes"]

Code example: parameter destructuring

A destructuring assignment can be used almost anywhere. We can even use them directly in function parameters.

const head = ([first]) => first

Test yourself

Description

Define a new function with the name

last

that takes an array input parameter list and returns the last element in the list.

Tests

  1. 1 You should define a function named last.
  2. 2last([100,200,300]) should return 300.
  3. 3last("strings are also indexable") should return "e".
  4. 4last(["The","Church","of","the","Survivor"]) should return "Survivor".
  5. 5last([]) should return undefined.
Editor