Skip to main content

JavaScript Arrays

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn about arrays and array methods in JavaScript.

An array in JavaScript is a special type of object that allows you to store multiple values in a single variable. Each value in the array is called an element, and elements are indexed starting at 0.

Creating an Array

The simplest way to create a JavaScript array is by using an array literal.

Syntax:

let arrayName = [element1, element2, ...];

Example:

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Using let allows reassignment, while const ensures the array reference remains unchanged.

Example:

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); 
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Using the JavaScript new Keyword

Another way to create an array:

const fruits = new Array("Apple", "Banana", "Cherry");
console.log(fruits); 
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Accessing Array Elements

Retrieve an element using its index:

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple

Last element:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits[fruits.length - 1]); // Output: Mango

Changing an Array Element

Modify a specific index:

const colors = ["Red", "Green", "Blue"];
colors[1] = "Yellow";
console.log(colors); 
// Output: Array(3) [ "Red", "Yellow", "Blue" ]

Converting an Array to a String

Use toString() to convert an array into a string:

const fruits = ["Apple", "Banana", "Cherry"];
let result = fruits.toString();
console.log(result); 
// String output: "Apple,Banana,Cherry"

The join() method allows specifying a separator:

console.log(fruits.join(" - ")); 
// String output: Banana - Orange - Apple - Mango

Arrays are Objects

Arrays in JavaScript are objects:

console.log(typeof []); // Output: object

Arrays use numeric indices, while objects use named properties:

const person = { firstName: "Robbin", lastName: "Zoo", age: 56 };
console.log(person.firstName); // Output: Robbin

Array Elements can be Objects

Arrays can hold objects:

const people = [
 { name: "Robbin", age: 30 },
 { name: "Jane", age: 25 },
 { name: "Doe", age: 35 }
];
console.log(people[0].name); // Output: Robbin
console.log(people[1].age);  // Output: 25

Questions & Answers