Skip to main content

Command Palette

Search for a command to run...

Arrays In JavaScript

Updated
2 min readView as Markdown
Arrays In JavaScript

In JavaScript, an array is a single variable used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

Why Use Arrays?

If you have a list of items (a list of color names, for example), storing the colors in single variables could look like this:

let color1= "Red";
let color2 = "Yellow";
let color3 = "DarkGreen";
let color4 = "Violet";
let color5 = "Blue";

Creating an Array

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];

Changing an Array Element

const colors[0] = "Brown";

Result:

["Brown", "Yellow", "DarkGreen","Violet","Blue"];

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Access the Full Array

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];

for(let element of colors){
    console.log(element);
}

Output:

Red
Yellow
DarkGreen
Violet
Blue

The length Property

The length property of an array returns the number of array elements.

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];

const lenthOfColors = colors.length;
console.log(lenthOfColors);

Result:

5

Output the First Element of the color Array

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];

console.log(colors[0]);

Result:

Red

Adding Array Element

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];
colors.push("Gray");
console.log(colors);

Result:

[ 'Red', 'Yellow', 'DarkGreen', 'Violet', 'Blue', 'Gray' ]

Remove Last Element of an Array

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];
colors.pop();
console.log(colors);

Result: The last element "Blue" is removed from the color array. Now color array does not have "Blue" element.

[ 'Red', 'Yellow', 'DarkGreen', 'Violet' ]

Merging (Concatenating) Arrays

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];
const Newcolors= ["BlueViolet", "Purple", "LightGreen","Lime","DarkBlue"];

const extraColors = colors.concat(Newcolors);

console.log(extraColors);

Output:

[
  'Red',       'Yellow',
  'DarkGreen', 'Violet',
  'Blue',      'BlueViolet',
  'Purple',    'LightGreen',
  'Lime',      'DarkBlue'
]

JavaScript Array forEach()

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

const colors= ["Red", "Yellow", "DarkGreen","Violet","Blue"];

colors.forEach(color => console.log(color));

Output:

Red
Yellow
DarkGreen
Violet
Blue

The forEach() method calls a function for each element in an array.

The forEach() method is not executed for empty elements.

30 views