JavaScript arrays

by Charlie Jackson


Posted on 16 May 2019 at 11:00 AM


code showing a JavaScript array

In this tutorial we'll be focusing specifically on JavaScript arrays starting from the very basics and gradually covering properties and methods of arrays.

What is an array

Storing data is a fundamental concept in programming. In JavaScript we can store data in an array - this is essentially the same as a having a list. You can store any data type including strings, Booleans, integers, floats and objects. Furthermore, you can nest data within a array to make more complex data structures. To create an array, you simply declare your variable and assign to '[]'

let shopping_list = ['onions', 'garlic', 'chilli','ginger']
        

Indexing arrays

You can access given elements within an array via their index with bracket notation. JavaScript arrays are zero indexed - so they begin at 0 instead of 1. Using our 'shopping_list' variable above we can access the given items via their index:

let shopping_list = ['onions', 'garlic', 'chilli','ginger']
console.log(shopping_list[0]); // returns 'onions'
console.log(shopping_list[2]); // returns 'chilli'
				

Nested arrays

Arrays can also be nested - i.e. putting one array into another. To retrieve an item inside a nested array you can chain the index values together.

let numbers = [[1,2,3], [4,5,6], [7,8,9]];

let numbers_1 = numbers[0];
let numbers_2 = numbers[1];
let numbers_3 = numbers[2];

console.log(numbers_1); // returns [1,2,3]

console.log(numbers[0][1]); returns 2
				

Updating arrays

Data within the array can be updated by assigning the given item to a new value.

let shopping_list = ['onions', 'garlic', 'chilli','ginger']
shopping_list[3] = 'lemon grass';
console.log(shopping_list); // returns ['onions', 'garlic', 'chilli','lemon grass'];
			

Reassigning arrays - difference in 'let' and 'const'

Variables in JavaScript are declared using 'let' or 'const' - the difference being that variables declared with 'let' can be changed whereas 'const' must remain the same. This is concept is true for arrays. However, arrays are always mutable even when declared with 'const' - by mutable, I mean as we have updated the array above. See the two examples - the first showing reassignment, the second showing array mutability.

Reassignment test:
let root_vegetables = ['carot', 'potatoe', 'squash'];
const fruit = ['lemon', 'lime', 'apple'];

// reassignment for variable declared using 'let'
root_vegetables = ['pumpkin'];
console.log(root_vegetables); // returns 'pumpkin'

// reassignment attempt for variable declared using 'const'
const fruit = ['pineapple'];
console.log(fruit);  // returns error - Uncaught TypeError: Assignment to constant variable
			
Mutability test:
let root_vegetables = ['carot', 'potatoe', 'squash'];
const fruit = ['lemon', 'lime', 'apple'];

root_vegetables[0] = 'pumpkin';
fruit[0] = 'pineapple';

console.log(fruit); // returns ['pumpkin', 'potatoe', 'squash'];
console.log(root_vegetables); // returns ['pineapple', 'lime', 'apple'];
			

Array properties / attributes

Arrays have built in properties which you can access with dot notation - i.e. 'array.length'. There are a number of array properties which can be found at Mozilla Developer Network.

let fruit = ['apple', 'bananna'];
console.log(fruit.length); // returns 2
				

Array methods

Arrays also have built in methods to do things such as add, remove, slice an array. A method is essentially the same as a function but it is tied specifically to the array. To call a method you first specify the array followed by dot notation and then by the method name - i.e. 'array.pop()'. Note you must provide the parenthesis at the end (as you would a function) - the parenthesis are the difference between calling an property / attribute and a method.

Mutator methods

As suggested in the title, mutator methods change the array - this can be by adding new items, removing items, slicing items and many more.

let fruit = ['apple', 'bananna'];

// push method - adds item to the end of the array
fruit.push('orange');
console.log(fruit); // returns ['apple', 'bananna', 'orange']

// pop method - removes item from the end of the array
fruit.pop();
console.log(fruit); // returns ['apple', 'bananna'] - orange was removed

// shift method - removes item from the start of the array
fruit.shift();
console.log(fruit); // returns ['bananna']
				

Iteration methods

Iteration methods are ways to loop through the array to produce the desired output. They are slightly more complex in nature. The syntax is similar - first you specify the array and then you call the method. However, the iteration methods take callback functions as their parameters. Lets take a look at an example usin the 'forEach()' method.

.foreach() method:
const fruits = ['apple', 'bananna', 'orange'];

fruits.forEach(function(fruit)
	{
	console.log(fruit); // returns apple, bananna, orange
	});
				

Firstly we call the 'forEach()' method on the array. We then pass a callback function as the parameter - this means each iteration is passed into the callback function parameter. Note, you could refactor the callback function as below (see my JavaScript functions tutorial for more information).

const fruits = ['apple', 'bananna', 'orange'];
fruits.forEach(fruit => console.log(fruit));
				

Another type of iteration method is the 'map()' method. This works nearly exactly the same way as 'forEach()' method accept it returns a new array. If you know Python, it is similar to list comprehension.

.map() method:
const fruits = ['apple', 'bananna', 'orange'];

const fruits_uppercase = fruits.map(function(fruit)
	{
	return fruit.toUpperCase();
	});

console.log(fruits_uppercase); // returns ['APPLE', 'BANANNA', 'ORANGE'];

// In one line of code:
// const fruits_uppercase = fruits.map(fruit => fruit.toUpperCase());
				

Another common method is the '.filter()' method. Like the .map() method it also returns an array but uses conditional logic to filter items out of the array.

.filter() method:
const fruits = ['apple', 'bananna', 'orange'];

const fruits_filter = fruits.filter(function(fruit)
	{
	return fruit.length > 5;
	});

console.log(fruits_filter); // returns ["bananna", "orange"]
				

There are a number of other array methods - you can find these at Mozilla Developer Network.


Looping through arrays

Know we know how to access items in an array using its index as well as calling array properties, we can loop through an array. First, we start by creating the array. Then we start a for loop - we create a new variable called 'i' (for 'iteration' - this is a convention), specify the condition using the array property 'length' and increment 'i' after every loop. We then access each item in the array using its index based upon 'i'.

let fruit = ['apple', 'bananna', 'orange'];

for (let i=0; i < fruit.length; i++)
	{
	console.log(fruit[i]); // returns apple, bananna, orange
	}
				

Using arrays with functions

Arrays can also be passed into a function as the parameter. Within the function the array methods can be called to make changes to the array.

Removing an item to an array using a function:
let fruit = ['apple', 'bananna', 'orange'];

function remove_item(arr)
	{
	arr.pop();
	}

remove_item(fruit);
console.log(fruit); // returns ['apple', 'bananna']
				
Adding an item to an array using a function:
let fruit = ['apple', 'bananna', 'orange'];

function add_item(arr, fruit)
	{
	arr.push(fruit);
	}

add_item(fruit, 'grapes');
console.log(fruit); // returns ["apple", "bananna", "orange", "grapes"]
				
Categories
Web development
About me

My name is Charlie Jackson, and I currently work as a technical SEO in a small digital marketing agency. Through working in SEO I discovered Python, and all the beautiful applications that it could be used for; in the world of SEO we are often crawling websites, scraping data, text mining and much more, which Python is fantastic for. I am only fairly new to programming, and there are a number of topics I am hoping to blog about including:

  • Data science; with python, SQL and possibly R
  • Machine learning with python
  • Natural language processing
  • SEO
  • Web development

As noted, I am not a developer or data scientist although I am eager to learn as much as possible, and apply to my background in SEO. I am largely writing this blog for myself to document my studies (and use as a code base), although it it happens to help somebody else that would be great.

Feel free to drop me a line: charlieojackson at gmail dot com.