Arrays
Explore arrays, how to create and manipulate them, access elements, and use array methods.
JavaScript Arrays Essentials
Creating Arrays
In JavaScript, an array is an ordered collection of values, which can be of any data type (numbers, strings, booleans, objects, even other arrays!). Arrays are a fundamental data structure used to store and manipulate lists of data.
There are two primary methods for creating arrays in JavaScript:
1. Array Literals
Array literals provide a concise and often preferred way to create arrays. You define an array by enclosing a comma-separated list of values within square brackets []
.
// Creating an empty array
let emptyArray = [];
// Creating an array of numbers
let numbers = [1, 2, 3, 4, 5];
// Creating an array of strings
let fruits = ["apple", "banana", "orange"];
// Creating an array of mixed data types
let mixedArray = [1, "hello", true, {name: "John"}];
Each value within the array is called an element, and each element has an index, starting from 0 for the first element. You can access elements of the array using their index within square brackets.
let firstFruit = fruits[0]; // firstFruit will be "apple"
let thirdNumber = numbers[2]; // thirdNumber will be 3
2. The Array
Constructor
The Array
constructor is another way to create arrays, although it's generally less common than using array literals.
// Creating an empty array using the Array constructor
let emptyArrayConstructor = new Array();
// Creating an array with a specified size (all elements will be undefined)
let sizedArray = new Array(5); // Creates an array with 5 elements, all initially undefined. Avoid this approach.
// Creating an array with specific elements using the Array constructor
let numbersConstructor = new Array(1, 2, 3, 4, 5); // Similar to using array literals in this case.
Important Note: When you pass a single number to the Array
constructor, it interprets that number as the desired size of the array, *not* as an element of the array. This can lead to unexpected behavior, so using array literals is generally recommended. For example, new Array(5)
creates an array with a length of 5, where each element is undefined
. This is different than [5]
, which creates an array with a single element, the number 5.
For clarity and to avoid confusion, use array literals []
whenever possible when creating arrays with specific elements.