Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
2 min read

In this article, we get to know about the array in js , basics about the array , how to access the elements in the array and a lot more.

What is Array?

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name.

  • JavaScript arrays are resizable and can contain a mix of different data types.

  • JavaScript array-copy operations create shallow copies. (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies).

How to Create an Array

Creating an array is simple. We use square brackets [] and separate our items with commas.

JavaScript

// Creating an array of favorite fruits
let fruits = ["Apple", "Banana", "Cherry", "Mango"];

By using one variable (fruits), we’ve successfully grouped four pieces of information together.

Accessing array elements

Each element in an array has a position called an index. Array indexing starts from 0.

let fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Cherry

Changing Array Values

You can modify any element using its index.

let fruits = ["Apple", "Banana", "Cherry"];

fruits[1] = "Mango";

console.log(fruits);
// ["Apple", "Mango", "Cherry"]

Finding Array Length

To find the total number of elements in an array, we use the length property.

let fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits.length); // 3

Looping Over Arrays

The real power of arrays comes when you combine them with loops. Instead of writing console.log five times, you can use a for loop to go through the entire collection automatically.

let colors = ["Red", "Green", "Blue", "Yellow"];

for (let i = 0; i < colors.length; i++) {
    console.log("Color " + i + " is " + colors[i]);
}

Conclusion

At the end, with this article we can learn about the basics of array and can learn about how to acces the element from the array , about indexing and how to loop over the arrays.