JavaScript arrays
Arrays in JavaScript are used to store multiple values in a single variable. They are a fundamental data structure that allows you to work with collections of data efficiently. Arrays in JavaScript are dynamic, meaning they can grow and shrink in size as needed, and they can hold elements of any type, including other arrays.
Creating Arrays
You can create arrays in several ways:
Array Literal Syntax
let fruits = ['apple', 'banana', 'cherry'];
Array Constructor
let numbers = new Array(1, 2, 3, 4, 5);
- You can also create an array with a specific length using
new Array(length)
, but this creates an array with empty slots, not values.
let emptyArray = new Array(5); // Creates an array with 5 empty slots
- You can also create an array with a specific length using
Accessing Elements
Array elements are accessed using zero-based indexing:
let colors = ['red', 'green', 'blue'];
console.log(colors[0]); // Outputs: 'red'
console.log(colors[1]); // Outputs: 'green'
Array Properties and Methods
Arrays come with several useful properties and methods:
Length Property
- The
length
property returns the number of elements in the array.
let animals = ['lion', 'tiger', 'bear']; console.log(animals.length); // Outputs: 3
- The
Push and Pop Methods
push()
: Adds one or more elements to the end of the array and returns the new length.
let stack = [1, 2, 3]; stack.push(4); // stack is now [1, 2, 3, 4]
pop()
: Removes the last element from the array and returns it.
let stack = [1, 2, 3]; let last = stack.pop(); // last is 3, stack is now [1, 2]
Shift and Unshift Methods
shift()
: Removes the first element from the array and returns it.
let queue = [1, 2, 3]; let first = queue.shift(); // first is 1, queue is now [2, 3]
unshift()
: Adds one or more elements to the beginning of the array and returns the new length.
let queue = [2, 3]; queue.unshift(1); // queue is now [1, 2, 3]
Slice and Splice Methods
slice(start, end)
: Returns a shallow copy of a portion of an array into a new array object.
let fruits = ['apple', 'banana', 'cherry', 'date']; let citrus = fruits.slice(1, 3); // citrus is ['banana', 'cherry']
splice(start, deleteCount, item1, item2, ...)
: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
let numbers = [1, 2, 3, 4, 5]; numbers.splice(2, 1, 'a', 'b'); // numbers is now [1, 2, 'a', 'b', 4, 5]
ForEach Method
forEach(callback)
: Executes a provided function once for each array element.
let numbers = [1, 2, 3]; numbers.forEach(num => console.log(num)); // Logs: 1, 2, 3
Map and Filter Methods
map(callback)
: Creates a new array with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3]; let doubled = numbers.map(num => num * 2); // doubled is [2, 4, 6]
filter(callback)
: Creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(num => num % 2 === 0); // evenNumbers is [2, 4]
Find and Reduce Methods
find(callback)
: Returns the first element that satisfies the provided testing function.
let numbers = [1, 2, 3, 4, 5]; let firstEven = numbers.find(num => num % 2 === 0); // firstEven is 2
reduce(callback, initialValue)
: Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
let numbers = [1, 2, 3, 4]; let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // sum is 10
Iterating Over Arrays
You can use various methods to iterate over arrays:
for
Looplet array = [1, 2, 3]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }
for...of
Looplet array = [1, 2, 3]; for (let value of array) { console.log(value); }
forEach
Methodlet array = [1, 2, 3]; array.forEach(value => console.log(value));
Summary
- Arrays: Used to store multiple values in a single variable.
- Creation: Can be created using literals or the
Array
constructor. - Access: Elements are accessed using zero-based indexing.
- Methods: Include
push
,pop
,shift
,unshift
,slice
,splice
,map
,filter
,find
,reduce
, and more. - Iteration: Can be done using
for
,for...of
,forEach
, and other methods.