How to make an array in JavaScript

Find out how to create an array in JavaScript with an example and use it in your code.

Creating an Array in JavaScript

An array is a special type of data structure in JavaScript that can store multiple values. It's like a list of items that you can access through an index number. Each item in an array is called an element. You can create an array by enclosing the elements in square brackets and separating them with commas.


var myArray = [1, 2, 3, 4, 5];

The above code will create an array containing five elements. You can access any element in the array by using its index. The index of the first element is 0 and the last element is the length of the array minus one.


var firstElement = myArray[0]; // 1
var lastElement = myArray[myArray.length - 1]; // 5

You can also add new elements to the array. All you need to do is assign a value to a new index. The index must be a number and it must be greater than or equal to the length of the array.


myArray[myArray.length] = 6;

The above code will add a new element with the value 6 to the end of the array. You can also use the push() method to add new elements to the end of an array.


myArray.push(7);

The push() method will add a new element with the value 7 to the end of the array. You can also use the unshift() method to add new elements to the beginning of an array.


myArray.unshift(0);

The unshift() method will add a new element with the value 0 to the beginning of the array. You can also remove elements from an array. All you need to do is use the splice() method.


myArray.splice(2, 1); // remove one element at index 2

The splice() method will remove the element at index 2 in the array. You can also use it to replace elements in an array.


myArray.splice(2, 1, 3); // replace element at index 2 with the value 3

The splice() method will replace the element at index 2 in the array with the value 3. You can also use the sort() method to sort the elements in an array.


myArray.sort();

The sort() method will sort the elements in the array in ascending order. You can also use it to sort the elements in descending order.


myArray.sort().reverse();

The above code will sort the elements in the array in descending order. You can also use the filter() method to filter out elements in an array.


var evenNumbers = myArray.filter(function(num) {
  return num % 2 == 0;
});

The above code will create a new array containing only the even numbers from the original array. You can also use the map() method to transform the elements in an array.


var doubleNumbers = myArray.map(function(num) {
  return num * 2;
});

The above code will create a new array containing the double of each element in the original array. These are just some of the ways you can use arrays in JavaScript. There are many more methods and options available for working with arrays.

Answers (0)