How to Use Array in JavaScript

2 min read
How to Use Array in JavaScript

Array in JavaScript is used to store an ordered collection of values. These values can be of any data type and can be 0 or more in numbers.

Usually, arrays are used to hold a similar types of values since it makes it easy to understand and iterate over.

Array values are comma-separated and enclosed in square braces i.e. []

The index of the array starts from 0 and you can access a value by its index.

Array’s size can be got with length property.

const names = ["John", "Michael", "Lewis", "Jordan"]
console.log(names.length) // 4
const ages = [45, 54, 30, 59]
console.log(ages.length) // 4
const participated  = [true, true, false, true]
console.log(participated.length) // 4
const errors = []
console.log(errors.length) // 0

Why Array? An array is useful when you have multiple values of similar type, and you want to iterate over them. If you have very few values then you may not use an array and declare the values one by one and access them directly, but what if these values grow to hundreds in number? This is where the array makes sense. It makes it easy for you to declare them and iterate over them in one go.

Declaring an array

There are mainly 2 ways of declaring an array.

  1. array literal
  2. new keyword (Array Constructor)

We will see both of them in detail.

array literal

Creating an array with an array literal is pretty simple. You can also have an array of objects. See the example below.

const cards = ["American Express", "Mastercard", "Visa"]

const card_status = []
card_status[0] = "Dispatched"
card_status[1] = "Received"
card_status[2] = "Declined"

const candidates = [
    {
        first_name: "John",
        cleared: true,
        age: 45
    },
    {
        first_name: "Jordan",
        cleared: false,
        age: 54
    },
    {
        first_name: "Davis",
        cleared: true,
        age: 30
    }
]

new keyword (Array Constructor)

Another way of creating an array is by using the new keyword i.e., instantiating an array using its constructor. Array items can be passed in the constructor directly or can be added later.

const cards = new Array("American Express", "Mastercard", "Visa")
console.log(cards.length) // 3

const cards = new Array()
console.log(cards.length) // 0
cards[0] = "American Express"
cards[1] = "Mastercard"
cards[2] = "Visa"
console.log(cards.length) // 3

const ages = new Array(45, 54, 30, 59)
console.log(ages.length) // 4

const ages1 = new Array(45)
console.log(ages1.length) // 45

Note The constructor which takes multiple integer arguments, each argument denotes an item. But if there is only one integer argument then it denotes the initial length of the array. However, this is not the case with a string argument. As a best practice, arrays should be declared using array literal.

Adding items to the array

Once you have declared an array, the next step is to add items to it. You can do this by using the following methods.

push(), This function adds element(s) to the end of the array. This function takes one or more items as arguments and returns the new length of the array.

const cards = ["American Express", "Mastercard", "Visa"]
let newLength = cards.push("Discover")
console.log(newLength) // 4
console.log(cards.length) // 4
console.log(cards[3]) // Discover

Accessing an array

There are various ways you can access elements of an array regardless of whether you declared the array using a literal or constructor. The following ways apply to both types of declarations.

Array index, You can access elements by using an index. Array index starts from 0 and goes till array.length – 1

const cards = ["American Express", "Mastercard", "Visa"]
        console.log(cards[0]) // American Express
        console.log(cards[1]) // Mastercard
        console.log(cards[2]) // Visa
        console.log(cards[3]) // undefined
        console.log(cards[cards.length - 1]) // Visa

Note – The index 3 exceeds the array length hence returns undefined when accessed.

for loop, You can access all the elements of an array using traditional for loop.

const cards = ["American Express", "Mastercard", "Visa"]
for (let i = 0; i < cards.length; i++) {
    console.log(cards[i])
}
// American Express
// Mastercard
// Visa

for of loop, you can access array elements using for of loop.

const cards = ["American Express", "Mastercard", "Visa"]
for (const card of cards) {
    console.log(card)
}
// American Express
// Mastercard
// Visa

forEach() Array elements can be accessed with forEach() function. This function takes a callback function as an argument.

const cards = ["American Express", "Mastercard", "Visa"]
cards.forEach((value) => console.log(value))
// American Express
// Mastercard
// Visa

map(), You can access array elements using map() function also which takes a callback function as an argument. This is the most common method of accessing an array.

const cards = ["American Express", "Mastercard", "Visa"]
cards.map(value => console.log(value))
// American Express
// Mastercard
// Visa

Array of objects

In our examples so far, we have seen an array of strings, but an array can also contain objects. In that case, the ways of accessing the array elements will be the same. This time they will return object when you access them by index or iterate over them.