JavaScript Arrays With Example

JavaScript Arrays With Example

In this tutorial, you will learn about JavaScript arrays with the help of examples. An array is a type of object that may hold several values at the same time. As an example:

const words = ['hello', 'world', 'welcome'];

Word is an array in this case. The array contains three values.

Create an Array

There are two ways to make an array:

1. Using an array literal

Using an array literal [] is the simplest way to create an array. As an example:

const array1 = ["eat", "sleep"];

2. Using the new keyword

You can also use the new keyword in JavaScript to construct an array.

const array2 = new Array("eat", "sleep");

In each of the above examples, we built an array with two elements.

Now: To generate an array, it is best to use an array literal.

Here are more examples of arrays:

// empty array
const myList = [ ];

// array of numbers
const numberArray = [ 2, 4, 6, 8];

// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];

// array with mixed data types
const newData = ['work', 'exercise', 1, true];

An array can also contain arrays, functions, and other objects. As an example:

const newData = [
    {'task1': 'exercise'},
    [1, 2 ,3],
    function hello() { console.log('hello')}
];

Access Elements of an Array

Array items can be accessed using indices (0, 1, 2,…). As an example:

const myArray = ['h', 'e', 'l', 'l', 'o'];

// first element
console.log(myArray[0]);  // "h"

// second element
console.log(myArray[1]); // "e"

Note: Array’s index starts with 0, not 1.

Add an Element to an Array

To add elements to an array, use the built-in methods push() and unshift().

The push() method adds an element to the array’s end. As an example:

let dailyActivities = ['eat', 'sleep'];

// add an element at the end
dailyActivities.push('exercise');

console.log(dailyActivities); //  ['eat', 'sleep', 'exercise']

The unshift() method adds one element to the array’s beginning. As an example:

let dailyActivities = ['eat', 'sleep'];

//add an element at the start
dailyActivities.unshift('work'); 

console.log(dailyActivities); // ['work', 'eat', 'sleep']

Change the Elements of an Array

By accessing the index value, you can also add or change items.

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise';

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']

Assume an array contains two elements. If you attempt to insert an element at index 3 (the fourth element), the third element will be undefined. As an example:

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise';

console.log(dailyActivities); // ["eat", "sleep", undefined, "exercise"]

In other words, if you try to add elements to high indices, the indices in between will have an undefined value.

Remove an Element from an Array

To delete the last element from an array, use the pop() method. The returned value is also returned by the pop() method. As an example:

let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();

//get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities);  // ['work', 'eat']

You can use the shift() method to delete the first element. The shift() method removes the first element and returns the element that was removed. As an example:

let dailyActivities = ['work', 'eat', 'sleep'];

// remove the first element
dailyActivities.shift();

console.log(dailyActivities); // ['eat', 'sleep']

Array length

The length property can be used to determine the length of an element (the number of elements in an array). As an example:

const dailyActivities = [ 'eat', 'sleep'];

// this gives the total number of elements in an array
console.log(dailyActivities.length); // 2

Array Methods

There are several array methods available in JavaScript that make it easy to conduct useful computations.

Among the most common JavaScript array methods are:

MethodDescription
concat()joins two or more arrays and returns a result
indexOf()searches an element of an array and returns its position
find()returns the first value of an array element that passes a test
findIndex()returns the first index of an array element that passes a test
forEach()calls a function for each element
includes()checks if an array contains a specified element
push()adds a new element to the end of an array and returns the new length of an array
unshift()adds a new element to the beginning of an array and returns the new length of an array
pop()removes the last element of an array and returns the removed element
shift()removes the first element of an array and returns the removed element
sort()sorts the elements alphabetically in strings and in ascending order
slice()selects the part of an array and returns the new array
splice()removes or replaces existing elements and/or adds new elements

Example: JavaScript Array Methods

let dailyActivities = ['sleep', 'work', 'exercise']
let newRoutine = ['eat'];

// sorting elements in the alphabetical order
dailyActivities.sort();
console.log(dailyActivities); // ['exercise', 'sleep', 'work']

//finding the index position of string
const position = dailyActivities.indexOf('work');
console.log(position); // 2

// slicing the array elements
const newDailyActivities = dailyActivities.slice(1);
console.log(newDailyActivities); // [ 'sleep', 'work']

// concatenating two arrays
const routine = dailyActivities.concat(newRoutine);
console.log(routine); // ["exercise", "sleep", "work", "eat"]

Note: If the element is not in an array, indexof() gives -1.

Working on JavaScript Arrays

An array is a type of object in JavaScript. Array indices are also objects.

Array items are kept by reference because they are objects. As a result, when an array value is copied, all changes in the copied array are mirrored in the original array. As an example:

let arr = ['h', 'e'];
let arr1 = arr;
arr1.push('l');

console.log(arr); // ["h", "e", "l"]
console.log(arr1); // ["h", "e", "l"]

You can also store values in an array by passing a named key. As an example:

javascript arrays javascript arrays javascript arrays javascript arrays javascript arrays javascript arrays javascript arrays

let arr = ['h', 'e'];
arr.name = 'John';

console.log(arr); // ["h", "e"]
console.log(arr.name); // "John"
console.log(arr['name']); // "John"

It is not suggested, however, to store values in an array by passing arbitrary names.

As a result, if the data are in an ordered collection, you should use an array in JavaScript. Otherwise, object with is preferable.

You may like:

continue and break Statements in JavaScript

Leave a Reply