Arrays in JavaScript

Henna Singh
5 min readMar 30, 2022
#BuildTogether Day 52/100

Today was a little stressful and unhappy day. Well, I blame the Irish weather, too much wind and cold :P

Although chicken and coffee for dinner was great ;)

Arrays

Organizing and storing data is a foundational concept of programming.

Arrays are JavaScript’s way of making lists. Arrays can store any data types (including strings, numbers, and booleans). Like lists, arrays are ordered, meaning each item has a numbered position.

let newYearsResolutions = ['Keep a journal', 'Take a falconry class', 'Learn to juggle'];console.log(newYearsResolutions);

Creating an Array

One way we can create an array is to use an array literal. An array literal creates an array by wrapping items in square brackets [].

An array can hold all the same or different data types.

['element example' , 10, true]
  • Each content item inside an array is called an element.
  • Each element inside the array is a different data type.

Accessing Elements

Each element in an array has a numbered position known as its index. Individual items in an array can be accessed using their index, which is similar to referencing an item in a list based on the item’s position.

Arrays in JavaScript are zero-indexed, meaning the positions start counting from 0 rather than 1. Therefore, the first item in an array will be at position 0.

  • cities[0] will access the element at index 0 in the array cities. You can think of cities[0] as accessing the space in memory that holds the string 'New York'.
  • Trying to access the index beyond the last element will output undefined

Updating Elements

Updating array elements is easy. Once you have accessed the element specifying the index, as shown above, you can then update its value

let seasons = ['Winter', 'Spring', 'Summer', 'Fall'];

seasons[3] = 'Autumn';
console.log(seasons);
//Output: ['Winter', 'Spring', 'Summer', 'Autumn']

The .length property

One of an array’s built-in properties is length and it returns the number of items in the array.

The property is accessed in the following way:

const objectives = ['Learn a new languages', 'Read 52 books', 'Run a marathon'];console.log(objectives.length) //3

The .push() method

This method, .push() allows us to add items to the end of an array.

  • .push() can take a single argument or multiple arguments separated by commas.
  • The method .push() changes, or mutates, an array. The method .push() is referred to as a destructive array method since it changes the initial array.

The .pop() method

The method pop() removes the last item of an array.

const newItemTracker = ['item 0', 'item 1', 'item 2'];

const removed = newItemTracker.pop();

console.log(newItemTracker);
// Output: [ 'item 0', 'item 1' ]
console.log(removed);
// Output: item 2
  • .pop() does not take any arguments, it simply removes the last element of newItemTracker.
  • .pop() returns the value of the last element. In the example, we store the returned value in a variable removed to be used for later.
  • .pop() is a method that mutates the initial array.

More Array Methods

Some arrays methods that are available in JavaScript include: .join(), .slice(), .splice(), .shift(), .unshift(), and .concat() amongst many others. Using these built-in methods make it easier to do some common tasks when working with arrays.

Some of the methods in the below program

You can read about all of the array methods on the Mozilla Developer Network (MDN) array documentation.

Arrays and Functions

What happens if you change an array inside a function? Does the array keep the change after the function call or is it scoped to inside the function?

const flowers = ['peony', 'daffodil', 'marigold'];

function addFlower(arr) {
arr.push('lily');
}

addFlower(flowers);

console.log(flowers); // Output: ['peony', 'daffodil', 'marigold', 'lily']
  • The flowers array that has 3 elements.
  • The function addFlower() has a parameter of arr uses .push() to add a 'lily' element into arr.
  • Call addFlower() with an argument of flowers which will execute the code inside addFlower.
  • Check the value of flowers , it now includes the 'lily' element! The array was mutated!

When an array is passed into a function and mutated inside it, that change will be maintained outside the function as well. This concept is called pass-by-reference as what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.

Nested Arrays

Arrays can store other arrays. When an array contains another array it is known as a nested array.

Nested arrays can be accessed using bracket notation and specifying the index as shown in the example:

const nestedArr = [[1], [2, 3]];

console.log(nestedArr[1]); // Output: [2, 3]
console.log(nestedArr[1][0]); // Output: 2

Reviewing Arrays

  • Arrays are lists that store data in JavaScript.
  • Arrays are created with brackets [].
  • Each item inside of an array is at a numbered position, or index, starting at 0.
  • We can access one item in an array using its index, with syntax like: myArray[0].
  • We can also change an item in an array using its index, with syntax like myArray[0] = 'new string';
  • Arrays have a length property, which allows you to see how many items are in an array.
  • Arrays have their own methods, including .push() and .pop(), which add and remove items from an array, respectively.
  • Arrays have many methods that perform different tasks, such as .slice() and .shift(), you can find documentation at the Mozilla Developer Network website.
  • Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
  • Variables that contain arrays can be declared with let or const. Even when declared with const, arrays are still mutable. However, a variable declared with const cannot be reassigned.
  • Arrays mutated inside of a function will keep that change even outside the function.
  • Arrays can be nested inside other arrays.
  • To access elements in nested arrays chain indices using bracket notation

If you fancy reading my 100 Days which has been an incredible learning experience, feel free to drop by ❤

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Henna Singh
Henna Singh

Written by Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, and paper crafts. Currently doing Full Stack Diploma at Code Institute

No responses yet

Write a response