Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays

Updated
3 min read
JavaScript Arrays

Arrays :

JavaScript arrays are special objects that store ordered collections of values in a single variable, supporting mixed data types and dynamic resizing. They enable efficient handling of lists like user data, DOM elements, or API responses in web development.


Why Use Arrays?

Arrays group related data for easy access via zero-based indices (e.g., arr[0]), avoiding multiple variables like let a=1, b=2, c=3;.
They support built-in methods (push, map, filter) for common tasks like adding/removing items or transforming data, making code cleaner and scalable.
In dynamic apps, arrays handle variable-sized lists (e.g., shopping carts) without fixed limits, unlike primitives.

Now let's see the how we can create a simple array in JavaScript.


Creation of an array :

We can create an array using various types of ways :

let favMovies = ["Inception", "Matrix", "Lucy"] //creation of an array.

let favMovies = new Array("Inception", "Matrix", "Lucy") //using "new" keyword

let numbers = new Array(3) //it will create 3 empty slots in an array.

let numbers = Array.of(3, 6, 9) //it will create array of these numbers instead of 3 empty slots.

Accessing elements using index :

Accessing elements in an array uses square brackets [] with an index number—arrays start counting from 0, so first item is [0], second is [1], and so on.​

Basic Syntax

Declare array, then grab items by position: arrayName[index]. Reading or changing works the same way.

Example :

let favMovies = ["Inception", "Matrix", "Lucy"]
console.log(favMovies[1]) // "Matrix"
//Index starts from zero [0].

Updating Elements :

You update array elements in JavaScript by assigning a new value directly to a specific index using square bracket notation array[index] = newValue.

Or

Adding any new value to the array.

let favMovies = ["Inception", "Matrix", "Lucy"]
favMovies[2] = "Interstellar" //["Inception", "Matrix", "Interstellar"]

Array length property :

The array length property tells you exactly how many items are in your array—it's a read/write number you access with dot notation like array.length.

let favMovies = ["Inception", "Matrix", "Lucy", "Interstellar"]
console.log(favMovies.length) // 4

Basic Looping over Arrays :

Basic looping over arrays repeats code for each item—like visiting every house on your street automatically.

For Loop (Most Control)

Classic way using index counter from 0 to length-1:

for(let i = 0; i < favMovies.length; i++){
    console.log(favMovies[i]);  
}
6 views