JavaScript Arrays
An array is a special type of object used to store multiple values in a single variable. In JavaScript, arrays can hold items of different types (numbers, strings, objects, other arrays, etc.), and they are indexed by numbers starting from 0.
1️⃣ Creating Arrays
You can create arrays in a few different ways:
1.1 Using Array Literals (Most Common)
1.2 Using the Array
Constructor
1.3 Creating an Empty Array
Or using the Array
constructor:
2️⃣ Accessing Array Elements
You access the elements in an array using the index (starting from 0):
You can also use negative indices to access elements from the end of the array (using at()
method):
3️⃣ Modifying Arrays
You can modify the contents of an array directly by using the index:
4️⃣ Array Methods
JavaScript provides several built-in methods to manipulate arrays. Here are some of the most commonly used ones:
4.1 Adding Elements
-
push()
: Adds one or more elements to the end of the array. -
unshift()
: Adds one or more elements to the beginning of the array.
4.2 Removing Elements
-
pop()
: Removes the last element from the array and returns it. -
shift()
: Removes the first element from the array and returns it.
4.3 Modifying Elements at Specific Index
-
splice()
: Adds/removes elements at a specific index.Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...)
4.4 Finding Elements
-
indexOf()
: Returns the index of the first occurrence of a specified element, or-1
if not found. -
includes()
: Returnstrue
if the array contains a specified element, otherwisefalse
.
4.5 Iterating Over Arrays
-
forEach()
: Executes a provided function once for each element in the array. -
map()
: Creates a new array populated with the results of calling a provided function on every element in the array. -
filter()
: Creates a new array with all elements that pass the test implemented by the provided function. -
reduce()
: Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
4.6 Transforming Arrays
-
sort()
: Sorts the elements of the array in place (can be used to sort strings and numbers). -
reverse()
: Reverses the order of the elements in the array.
4.7 Flattening Arrays
-
flat()
: Flattens nested arrays into a single array.
5️⃣ Multidimensional Arrays
You can have arrays of arrays (multi-dimensional arrays). These are common when working with matrices or complex data structures.
6️⃣ Array Destructuring
You can also destructure arrays to assign values to variables:
You can skip elements and assign them directly:
7️⃣ Conclusion
Arrays are a fundamental part of JavaScript that allows you to store multiple values in a single variable and perform various operations on them. They are highly flexible and come with a wide range of built-in methods for sorting, iterating, and modifying the data they hold.
Let me know if you'd like more examples or explanations! 😊