Black Friday Sale is on: Get Amazing deals on tools and resourcess

Tutorial: Javascript Arrays


By Emmanuel Chinonso

Web Developer

JavaScript Arrays

Contrast Bootstrap UI Kit

Arrays in JavaScript are used to store several values in a single variable.

JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];

What is an Array?

An array is a type of variable that may store several values at the same time. If you have a list of objects (for example, a list of automobile names), storing the vehicles in single variables could look like this:

  • var car1 = "Saab";
  • var car2 = "Volvo";
  • var car3 = "BMW";

But what if you want to go through the automobiles one by one and find a certain one? What if you had 300 vehicles rather than three? An array is the solution! A single name can be used to store many values in an array, and the data can be accessed by referring to an index number.

Creating an Array:

The simplest approach to generate a JavaScript Array is to use an array literal.

Syntax: var array_name = [item1, item2, ...];

JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];

It is not necessary to use spaces or line breaks. A declaration can consist of numerous lines:

JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];

Using the JavaScript Keyword new: The following code also creates an Array, and assigns values to it:

JavaScript Code:

1var cars = new Array('Saab', 'Volvo', 'BMW');

The previous two instances do the same thing. It is not necessary to utilize new Array (). Use the first one(the array literal method) for simplicity, readability, and execution speed.

Access the Elements of an Array

The index number is used to access an array element. The value of the first element in cars is accessed by this statement. The indexes of arrays begin with 0. The first element is [0]. The second element is [1]. var name = cars[0];

JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];
2document.getElementById('demo').innerHTML = cars[0];

Changing an Array Element:

The value of the first element in vehicles is changed by this statement: cars[0] = "Opel"; JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];
2cars[0] = 'Opel';
3document.getElementById('demo').innerHTML = cars[0];

Access the Full Array: The complete array can be obtained in JavaScript by referring to the array name:

JavaScript Code:

1var cars = ['Saab', 'Volvo', 'BMW'];
2document.getElementById('demo').innerHTML = cars;

Arrays are Objects

Arrays are a type of object. For arrays, the typeof operation in JavaScript returns "object." However, JavaScript arrays are better described as arrays. Arrays employ numbers to access their "elements." In this case, person[0] returns John:


1var person = ['John', 'Doe', 46];

Objects use names to access their "members." In this case, person.firstName returns John:


1var person = { firstName: 'John', lastName: 'Doe', age: 46 };

Array Elements Can Be Objects Objects can be used as variables in JavaScript. Arrays are specialized types of objects. As a result, you can have variables of different types in the same Array. An array can contain objects. An Array can contain functions. Arrays can contain arrays:

1myArray[0] = Date.now;
2myArray[1] = myFunction;
3myArray[2] = myCars;

Array Properties and Methods: The built-in array attributes and methods are the real strength of JavaScript arrays:

JavaScript Code:

1var x = cars.length; // The length property returns the number of elements
2var y = cars.sort(); // The sort() method sorts arrays

The length Property

The length property of an array returns the array's length (the number of array elements). The length property is always one more than the array index with the highest value.

JavaScript Code:

1var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2fruits.length; // the length of fruits is 4

Accessing the First Array Element

JavaScript Code:

1fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2var first = fruits[0];

Accessing the Last Array Element JavaScript Code:

1fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2var last = fruits[fruits.length - 1];

Looping Array Elements: The safest way to loop through an array, is using a for loop:

JavaScript Code:

1var fruits, text, fLen, i;
2fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
3fLen = fruits.length;
5text = '<ul>';
6for (i = 0; i < fLen; i++) {
7 text += '<li>' + fruits[i] + '</li>';
9text += '</ul>';

You can also use the Array.forEach() function:

JavaScript Code:

1var fruits, text;
2fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
3text = '<ul>';
5text += '</ul>';
7function myFunction(value) {
8 text += '<li>' + value + '</li>';

Adding Array Elements: The push() method is the simplest way to add a new element to an array:

JavaScript Code:

1var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2fruits.push('Lemon'); // adds a new element (Lemon) to fruits

The length property can also be used to add new elements to an array.

Adding elements with high indices to an array can result in undefined "holes": JavaScript Code:

1var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2fruits[fruits.length] = 'Lemon'; // adds a new element (Lemon) to fruits

JavaScript Code:

1var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
2fruits[6] = 'Lemon'; // adds a new element (Lemon) to fruits

Associative Arrays

Arrays with named indexes are supported by a wide range of programming languages. Associative arrays are arrays with named indexes (or hashes). Arrays with named indexes are not supported by JavaScript. Arrays in JavaScript always utilize numbered indexes. When using named indexes, JavaScript will redefine the array to a normal object.

Following that, several array methods and properties will yield inaccurate results

JavaScript Code:

1var person = [];
2person[0] = 'John';
3person[1] = 'Doe';
4person[2] = 46;
5var x = person.length; // person.length will return 3
6var y = person[0]; // person[0] will return "John"

JavaScript Code:

1var person = [];
2person['firstName'] = 'John';
3person['lastName'] = 'Doe';
4person['age'] = 46;
5var x = person.length; // person.length will return 0
6var y = person[0]; // person[0] will return undefined

The Difference Between Arrays and Objects

  • Arrays in JavaScript employ numbered indexes.
  • Objects in JavaScript make use of named indexes.
  • Arrays are a type of object that has numbered indexes.

When to Use Arrays. When to use Objects.

Associative arrays are not supported by JavaScript. When you want the element names to be strings, you should use objects (text). When you want the element names to be numbers, you should use arrays

Avoid new Array() There is no need to utilize the built-in array constructor new Array in JavaScript ().

Instead, use [].

Both of these statements generate a new empty array named points:

1var points = new Array(); // Bad
2var points = []; // Good

Both of these statements generate a new array of 6 numbers:

1var points = new Array(40, 100, 1, 5, 25, 10); // Bad
2var points = [40, 100, 1, 5, 25, 10]; // Good

The new keyword only adds to the code's complexity. It can also have some unforeseen outcomes:

1var points = new Array(40, 100); // Creates an array with two elements (40 and 100)

What if I take one of the elements out?

1var points = new Array(40); // Creates an array with 40 undefined elements !!!!!.

Contrast Bootstrap UI Kit

Create Stunning websites and web apps

Trying to build out all user interfaces and components for your website or web app from scratch can become a very tedious task. A huge reason why we created Contrast Bootstrap to help reduce the amount of time we spend doing that, so we can focus on building some other aspects of the project. Contrast Bootstrap PRO consists of a UI Kit featuring over 10000+ component variants. Together with a template of 5 admin dashboards and 23+ additional multipurpose pages template for building almost any type of website or web app. You can view a demo and learn more about Contrast by clicking here.Try contrast pro


Contrast Bootstrap PRO was built using the most popular CSS framework Bootstrap to help build your next landing, admin SAAS, prelaunch etc project with a clean, prebuilt and well documented template and UI components.Learn more about Contrast

Related Posts