Trusted answers to developer questions

What are arrays in JavaScript?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

An array is an object used to store a collection. This collection could be anything: numbers, objects, more arrays, etc. In JavaScript, arrays are used to store multiple values in one variable that can be accessed through an index (which starts from zero). The values stored in the array are called elements and the number of elements stored in an array is typically referred to as the array’s length. For example, in the illustration given below, the length of the array is five:

An example of an array
An example of an array

How to declare and initialize an array?

In JavaScript, there are two ways to declare an array:

  • Declare using array literal
  • Declare using array constructor

1. Using array literal

This is the most basic way to declare and initialize an array in JavaScript:

var my_array = [1,3,5,2,4]
console.log(my_array)

2. Using array constructor

You can also declare an array using a JavaScript built-in Array class and initialize it by passing the values inside the brackets, like this:​

var my_array = new Array(1,3,5,2,4)
console.log(my_array)

How to access a value?

To access a particular element in an array, you will need to know the index of that element.

svg viewer

For example, if you want to access the fourth element, “2”, you would write:

var my_array = [1,3,5,2,4]
var my_element = my_array[3]
console.log(my_element)

How to modify an element in an array?

The syntax to modify a value at a particular index, let’s say 2, is this:

var my_array = [1,3,5,2,4]
console.log(my_array[2])
my_array[2] = 0
console.log(my_array[2])

Are arrays in JavaScript objects?

Yes, you read that right. Arrays in JavaScript are objects. If you look at the typeof of an array, it will return an object.

var my_array = [1,2,3,4,5]
console.log(typeof my_array)

RELATED TAGS

javascript
arrays
array
programming
data structures
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?