What is a Javascript Array?

The Array object in Javascript can store multiple values in a single variable. An array can store many values under a single name, and all the elements can be accessed using index numbers.

Unlike other languages, the Javascript array can hold variables of differernt data type as well.

Creating an Array

To create an array you can use the following format

var arrayName = ["ele1", "ele2", "ele3"];

var arrayName = [];

var sampleArray = ["batman", "superman", "spiderman", "wonderwoman", "ironman", 34, 56, "hawkeye", 1.21];

// input your custom array in the field below

// click on execute and slide the toggle to switch between your

// custom array and prebuilt sampleArray

Accessing an Array elements

To access any array element you can use the following format

arrayName[index of the element]

var zerothElement = arrayName[0];

Array index starts from 0

Consider the sample array, input different index number to access different values inside the array

Changing an Array element

To change any array element you can use the following format

arrayName[index of the element] = new value;

Consider the sample array, change the value of elements by mentioning the key and value

What are some Javascript Array methods?

The javascript offers a few inbuilt methods which we can use on the array.

Let's have a look at them.

Popping

Popping means, we are removing elements from an array

We use pop() method to remove the last element from an array.

var arrayName = ["ele1", "ele2", "ele3"];

arrayName.pop();

Shifting

Shifting means, we are removing elements from an array

We use shift() method to remove the first element from an array and all other elements shifts one position down in the index list (decrements the index value).

var arrayName = ["ele1", "ele2", "ele3"];

arrayName.shift();

Pushing

Pushing means, we are adding elements to an array

We use push() method to add an element to the end of an array.

var arrayName = ["ele1", "ele2", "ele3"];

arrayName.push("ele4");

Unshifting

Unshifting means, we are adding elements to an array

We use unshift() method to add an element to the start of an array.

var arrayName = ["ele1", "ele2", "ele3"];

arrayName.unshift("ele0");

Deleting

Deleting means, we are deleting an elements from an array.

We use delete method to delete an element and the deleted element will be reassigned as undefined or empty.

var arrayName = ["ele1", "ele2", "ele3"];

delete arrayName[0];

Please use the inspect tool to see the changes to the array: Ctrl + Shift + I

Javascript Sandbox

Please use the following text field to run, any Javascript code. The current status of the array will be shown after every execution.

// our array name is globalArray

// run any code you want, find the example below

globalArray.push("Krypto");

References

1. w3school Javascript Arrays