Arrays in Javascript


Published on 07 April 2022


Arrays in Javascript

Description and operation of arrays in Javascript

An array is a set of data ordered by positions, this data type being of any type, such as number, string, boolean,...
This set of data will be enclosed within square brackets, which will identify the array as a whole, where each element will be defined within quotes, unless it is a number or a boolean.

An array can have the following form:

var name_array = [first element, second element, third element];

Where each element has a position:

name_array = ["first element", "second element", "third element"];
                position 0        position 1        position 2

An array can be created in 3 ways:

  • Writing the name of the array inside a variable, followed by the elements and their values ​​in square brackets.

var house = [myHouse, 10, true];

  • Writing the name of the array inside a variable indicating the number of positions it will have without any established value.

var house = new Array(3);

  • Writing the name of the array inside a variable indicating the new array created with the values ​​inside.

var house = new Array(myHouse, 10, true);

In the following example we will show a script in javascript in which an array will be created and it will be seen how to access the elements inside it:

var colors = ["red", "white", "blue"];

To access position 0 of the array:

console.log(colours[0]); //Result: network

To access position 1 of the array:

console.log(colours[1]); //Result: white

To access position 2 of the array:

console.log(colours[2]); //Result: blue


In case we want to add elements to the colors array, we use the default method "push" with the name of the element to add:

colors.push("yellow");

This new element will be added in the next position of the array, that is, position 3.

console.log(colors[3]); //Result: yellow


Previous Chapter - Next Chapter



Tips on SEO and Online Business

Next Articles

Previous Articles