Why Use Arrays?
If you have a list of items (like car names), using separate variables would be inefficient:
let car1 = "Saab";let car2 = "Volvo";let car3 = "BMW";
Using arrays simplifies this process and makes it easier to manage a large number of items.
Creating an Array
Using an array literal is the simplest way to create a JavaScript array:
const arrayName = [item1, item2, ...];
Example
const cars = ["Saab", "Volvo", "BMW"];
You can also spread the declaration across multiple lines for better readability:
const cars = [ "Saab", "Volvo", "BMW"];
You can create an empty array and add elements later:const cars = [];
cars[0] = "Saab";cars[1] = "Volvo";cars[2] = "BMW";
Using the JavaScript Keyword new
You can create an array using the new keyword, but it's less common:
const cars = new Array("Saab", "Volvo", "BMW");
For simplicity and readability, it's recommended to use array literals.
Accessing Array Elements
Access array elements using their index number:
const cars = ["Saab", "Volvo", "BMW"];let car = cars[0]; // "Saab"
Changing an Array Element
You can change the value of an array element by referring to its index:
const cars = ["Saab", "Volvo", "BMW"];cars[0] = "Opel"; // "Opel", "Volvo", "BMW"
Converting an Array to a String
The toString() method converts an array to a comma-separated string:
const fruits = ["Banana", "Orange", "Apple", "Mango"];document.getElementById("demo").innerHTML = fruits.toString();// "Banana,Orange,Apple,Mango"
Access the Full Array
You can access the entire array by referring to the array name
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;// "Saab,Volvo,BMW"
Arrays are Objects
Arrays are a special type of object in JavaScript. The typeof operator returns "object" for arrays.
Arrays use numbered indexes to access their elements:
const person = ["John", "Doe", 46];console.log(person[0]); // "John"
Objects use named indexes:
const person = {firstName: "John", lastName: "Doe", age: 46};
console.log(person.firstName); // "John"
Array Elements Can Be Objects
You can store objects, functions, and even other arrays inside an array:
const myArray = [];myArray[0] = Date.now;myArray[1] = function() { return "Hello"; };myArray[2] = ["Saab", "Volvo", "BMW"];
Array Properties and Methods
- cars.length returns the number of elements in the array.
- cars.sort() sorts the array.
The length Property
The length property returns the number of elements in an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];let length = fruits.length; // 4
Accessing the First and Last Array Elements
First Element
const fruits = ["Banana", "Orange", "Apple", "Mango"];let fruit = fruits[0]; // "Banana"
Last Element
const fruits = ["Banana", "Orange", "Apple", "Mango"];let fruit = fruits[fruits.length - 1]; // "Mango"
Looping Array Elements
You can loop through an array using a for loop:
const fruits = ["Banana", "Orange", "Apple", "Mango"];let text = "<ul>";for (let i = 0; i < fruits.length; i++) { text += "<li>" + fruits[i] + "</li>";}text += "</ul>";Or using the forEach() method:
const fruits = ["Banana", "Orange", "Apple", "Mango"];let text = "<ul>";fruits.forEach(function(value) { text += "<li>" + value + "</li>";});text += "</ul>";
Adding Array Elements
Using push()
const fruits = ["Banana", "Orange", "Apple"];fruits.push("Lemon"); // ["Banana", "Orange", "Apple", "Lemon"]
Using length
const fruits = ["Banana", "Orange", "Apple"];fruits[fruits.length] = "Lemon"; // ["Banana", "Orange", "Apple", "Lemon"]
WARNING: Undefined "Holes" in Arrays
Adding elements with high indexes can create undefined "holes":
const fruits = ["Banana", "Orange", "Apple"];fruits[6] = "Lemon"; // ["Banana", "Orange", "Apple", undefined, undefined, undefined, "Lemon"]
Associative Arrays
JavaScript does not support arrays with named indexes. Using named indexes will redefine the array to an object:
const person = [];person["firstName"] = "John";person["lastName"] = "Doe";person["age"] = 46;console.log(person.length); // 0console.log(person[0]); // undefined
The Difference Between Arrays and Objects
- Arrays use numbered indexes.
- Objects use named indexes.
When to Use Arrays and Objects
- Use objects when element names are strings.
- Use arrays when element names are numbers.
JavaScript new Array()
JavaScript has a built-in array constructor new Array(), but it's recommended to use array literals.
Example
const points = new Array(40, 100, 1, 5, 25, 10);const points = [40, 100, 1, 5, 25, 10];
Using the new keyword can produce unexpected results:
const points = new Array(40); // Creates an array with 40 undefined elementsconst points = [40]; // Creates an array with one element: 40
How to Recognize an Array
Solution 1: Array.isArray()
const fruits = ["Banana", "Orange", "Apple"];Array.isArray(fruits); // true
Solution 2: instanceof
const fruits = ["Banana", "Orange", "Apple"];fruits instanceof Array; // true
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
Example
const myObj = { name: "John", age: 30, cars: [ {name: "Ford", models: ["Fiesta", "Focus", "Mustang"]}, {name: "BMW", models: ["320", "X3", "X5"]}, {name: "Fiat", models: ["500", "Panda"]} ]};
To access arrays inside arrays, use a for-in loop for each array:
let text = "";for (let i in myObj.cars) { text += "<h1>" + myObj.cars[i].name + "</h1>"; for (let j in myObj.cars[i].models) { text += myObj.cars[i].models[j] + " "; }}
This rephrased explanation should give a clear and comprehensive understanding of JavaScript arrays and how to work with them.