Arrays are used to store multiple values in a single variable. They store several pieces of data in one place. An array is an ordered collection of values. Each value is called an element and each element has a numeric position in the array known as its index.
An element inside an array can be of any type, and different elements of the same array can be of different types; string, boolean, numbers, objects, or even other arrays.
Arrays in JavaScript are zero-based which means that the first element in the array has an index of 0, and the second element has an index of 1, and so on.
Creating arrays
The most popular method for creating arrays is using the array literal syntax. It is the easiest way to create arrays in JavaScript.
Syntax:
var stack = ["HTML", "CSS", "JavaScript"];
An alternative method for creating arrays is using the array constructor (JavaScript new keyword)
Syntax:
var planets = new Array("Mars", "Mercury", "Earth");
Remember:
use array literals instead of the Array constructor for simplicity, readability, and execution speed.
the Array constructor behaves differently if its only argument is a number.
Array properties
1. Index
This property represents the zero-based index of the match in the string. It helps us access elements in the array.
Accessing elements in an array
const todo = ["pray", "code", "blog"];
// first element
console.log(todo[0]); // pray
// second element
console.log(todo[1]); // code
// last element
console.log(todo[todo.length - 1]); // blog
Changing elements in an array
You can also add or change elements by accessing the index value.
let artists = ["Pompi", "Laycon"];
artists[2] = "Limoblaze"; // adding another element
console.log(artists); // ["Pompi", "Laycon", "Limoblaze"]
artists[1] = "Mag44"; // changing the element
console.log(artists); // ["Pompi", "Mag44", "Limoblaze"]
2. The length property
The length property returns the length of the array (number of elements in the array). The length property simply returns the value of the biggest index + 1 for example;
const dailyActivities = ["eat", "work", "sleep"];
// total number of elements in the array
console.log(dailyActivities.length); // 3
Conclusion
In this article, we have looked at the different techniques to dynamically create arrays and properties used on arrays.