JavaScript Fundamentals / Arrays

Creating Arrays

📋 Understanding Arrays

An array in JavaScript is a special type of object designed to store multiple values in a single variable. It is useful for organizing collections of data, allowing you to store, access, and manage items efficiently using their index positions.

Key characteristics of JavaScript arrays are:

  • Elements: An array is a list of values, known as elements.

  • Ordered: Array elements are ordered based on their index.

  • Zero indexed: The first element is at index 0, the second at index 1, and so on.

  • Dynamic size: Arrays can grow or shrink as elements are added or removed.

  • Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects and other arrays).


⚡Why Use Arrays?

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

let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.


✅ Creating an Array using Literal

Creating an array using array literal involves using square brackets [ ] to define and initialize the array.

Syntax : const array_name = [item1, item2, ...];

const cars = ["Saab", "Volvo", "BMW"];
console.log(cars); //['Saab','Volvo','BMW']

Spaces and line breaks are not important. A declaration can span multiple lines.

const cars = [  
"Saab", 
"Volvo",  
"BMW"
]; 
console.log(cars); //['Saab','Volvo','BMW']

You can also create an empty array, and provide elements later.

const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";   
console.log(cars); //['Saab','Volvo','BMW']

✅ Create using new Keyword (Constructor)

The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor function.

let a = new Array(10, 20, 30);
console.log(a); //[ 10, 20, 30 ]