JavaScript arrays examples

JavaScript Array is a single variable that is used to store elements of different data types. JavaScript arrays are zero-indexed. The JavaScript Arrays are not associative in nature.

Arrays are used when we have a list of items. An array allows you to store several values with the same name and access them by using their index number.

Declaration of an Array

There are basically two ways to declare an array.

1. Creating an array using array literal:

let arrayName = [value1, value2, value3,....];

JavaScript

// Initializing while declaring
let courses = ["HTML", "CSS", "JavaScript", "React"];
console.log(courses)

Output [ ‘HTML’, ‘CSS’, ‘JavaScript’, ‘React’ ]


2. Creating an array using the JavaScript new keyword:

let arrayName = new Array();

JavaScript

// Initializing while declaring
let arr1 = new Array(3)
arr1[0] = 10
arr1[1] = 20
arr1[2] = 30
console.log("Array 1: ", arr1)
// Creates an array having elements 10, 20, 30, 40, 50
let arr2 = new Array(10, 20, 30, 40, 50);
console.log("Array 2: ", arr2)
// Creates an array of 5 undefined elements
let arr3 = new Array(5);
console.log("Array 3: ", arr3)
// Creates an array with one element
let arr4 = new Array("1BHK");
console.log("Array 4: ", arr4)

Output

Array 1:  [ 10, 20, 30 ]
Array 2:  [ 10, 20, 30, 40, 50 ]
Array 3:  [ <5 empty items> ]
Array 4:  [ '1BHK' ]

Note: Both the above methods do exactly the same. Use the array literal method for efficiency, readability, and speed.

Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts with 0.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
console.log(courses[0])
console.log(courses[1])
console.log(courses[2])

Output

HTML
CSS
Javascript

Change elements from a pre-defined array.

We will use index-based method to change the elements of array.

JavaScript

const courses = ["HTML", "CSS", "JavaScript"];
console.log(courses)
courses[1]= "CodeConfig.in"
console.log(courses)

Output

[ 'HTML', 'CSS', 'JavaScript']
[ 'HTML', 'CodeConfig.in', 'JavaScript']

Convert an Array to String

We have an in-built method toString() in JavaScript that converts an array to a string.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
console.log(courses.toString())

Output

HTML,CSS,Javascript

Increase and decrease the length of an array.

We can increase and decrease the length of an array using the JavaScript’s length property.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
courses.length = 5 // Increasing array length to 5
console.log("Array after increased length: " ,courses)
courses.length = 2 // Decreasing array length to 2
console.log("Array after decreased length: " ,courses)

Output

Array after increased length:  [ 'HTML', 'CSS', 'Javascript', <2 empty items> ]
Array after decreased length:  [ 'HTML', 'CSS' ]

We can also update an array after initialization.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
courses.length = 5 // Increasing array length to 5
console.log("Array after increased length: " ,courses)
courses[3] = 'PhP'
courses[4] = 'React'
console.log("Array after initializing: ", courses)

Output

Array after increased length:  [ 'HTML', 'CSS', 'Javascript', <2 empty items> ]
Array after initializing:  [ 'HTML', 'CSS', 'Javascript', 'PhP', 'React' ]

Loop through JavaScript Array Elements

We can loop through the elements of a JavaScript array using the for loop:

JavaScript

const courses = ["HTML", "CSS", "JavaScript"];
for (let i = 0; i < courses.length; i++) {
    console.log(courses[i])
}

Output

HTML
CSS
JavaScript

This can also be done by using the Array.forEach() function of JavaScript.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
courses.forEach(myfunc);
function myfunc(elements) {
    console.log(elements);
}

Output

HTML
CSS
JavaScript

Adding new elements to JavaScript Array

Using the JavaScript in-built push() method we can add new elements to an array.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
console.log("Original Array: ",courses)
courses.push("React")
console.log("Array after adding an element: ",courses)

Output

Original Array:  [ 'HTML', 'CSS', 'Javascript' ]
Array after adding an element:  [ 'HTML', 'CSS', 'JavaScript', 'React' ]

We can also add a new element to a JavaScript array using the length property.

JavaScript

const courses = ["HTML", "CSS", "Javascript"];
console.log("Original Array: ",courses)
courses[courses.length] = "React"
console.log("Array after adding an element: ",courses)

Output

Original Array:  [ 'HTML', 'CSS', 'Javascript' ]
Array after adding an element:  [ 'HTML', 'CSS', 'Javascript', 'React' ]

Finding the typeof JavaScript Arrays

The Javascript typeof operator returns “object” for arrays.

Javascript

const courses = ["HTML", "CSS", "Javascript"];
console.log(typeof courses)

Output

object


Difference between Javascript arrays and objects

Javascript arrays use indexes as numbers while objects use indexes as names.

When to use JavaScript Arrays and Objects?

Arrays are used when we want element names to be numeric while Objects are used when we want element names to be strings.

Recognizing a JavaScript Array

There are two methods by which we can recognize a JavaScript array:

  • By using Array.isArray() method
  • By using instanceof method 

Below is an example showing both approaches:

Javascript

const courses = ["HTML", "CSS", "Javascript"];
console.log("Using Array.isArray() method: ",Array.isArray(courses))
console.log("Using instanceof method: ",courses instanceof Array)

Output

Using Array.isArray() method:  true
Using instanceof method:  true

A common error is faced while writing the arrays:

const numbers = [5]
// and
const numbers = new Array(5) 

Javascript

const numbers = [5]
console.log(numbers)

The above two statements are not the same.

Output: This statement creates an array with an element ” [5] “.

[5]

JavaScript

const numbers = new Array(5)
console.log(numbers)

Output: This statement creates an array with five undefined elements.

[ <5 empty items> ]

For commonly used Array methods refer to the links below.

  • JavaScript Array Functions – Part 1
  • JavaScript Array Functions – Part 2
  • JavaScript Array Functions – Part 3

We have a complete list of JavaScript Array methods, to check those please go through this JavaScript Array reference article.

We have a Cheat Sheet on JavaScript where we covered all the important topics of JavaScript to check those please go through JavaScript Cheat Sheet-A Basic guide to JavaScript.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, codeconfig.in Courses are your key to success. We provide top-quality content at no cost, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!