HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Arrays

An array is a special variable that can hold more than one value at a time. It is used to store a collection of data, which makes it much easier to manage large lists of related information.


Why Use Arrays?

Imagine you have a list of cars. Storing them in single variables would look like this:

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

However, what if you had 300 cars? Finding a specific one would be a nightmare. An array allows you to store them all under a single name and access them using a number called an index.


Creating an Array

The most common way to create a JavaScript array is by using array literals (square brackets []).

const cars = ["Saab", "Volvo", "BMW"];
Note: It is standard practice to declare arrays with the const keyword, as the reference to the array should not change, even if you modify the elements inside.

Accessing Array Elements

You can access an array element by referring to its index number. Remember that JavaScript arrays are zero-based: the first element is [0], the second is [1], and so on.

const fruits = ["Banana", "Orange", "Apple"];
let fruit = fruits[0]; // Result: "Banana"

Changing an Array Element

You can change the value of a specific element by using its index:

const fruits = ["Banana", "Orange", "Apple"];
fruits[0] = "Mango"; 
// Now the first fruit is "Mango" instead of "Banana"

The length Property

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

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.length); // 4
Tip: You can use the length property to access the last element of any array: fruits[fruits.length - 1].

Arrays vs. Objects

In JavaScript, arrays use numbered indexes, while objects use named indexes. Arrays are a special type of object used for lists of data where the order matters.

  • Use Arrays when you want the element names to be numbers.
  • Use Objects when you want the element names to be strings (properties).

Key Points to Remember

  • An array stores multiple values in a single variable
  • Arrays are zero-indexed (first element is 0)
  • Use [index] to access or modify specific elements
  • The length property tells you how many items are in the array
  • Arrays are technically objects, but optimized for ordered lists
  • Always prefer [] over new Array() for better performance