Welcome to our deep dive into JavaScript (JS) Arrays! In this lesson, we'll learn everything you need to know about arrays, from the basics to advanced examples. 📝
Arrays are a special type of variable in JavaScript that can hold multiple values. They allow you to store and manipulate lists, collections, and sequences of data. 💡
Here's a simple example of an array:
// Declare an array with the name 'myArray'
const myArray = [1, 2, 3, 4, 5];In the above example, we've created an array called myArray containing five numbers. Each number is referred to as an element within the array.
To access an element in an array, you use its index number. In JavaScript, array indices start at 0. Let's access the first and last elements of our myArray:
// Access the first element
console.log(myArray[0]); // Output: 1
// Access the last element
console.log(myArray[myArray.length - 1]); // Output: 5You can change the value of an array element by assigning a new value to its index:
// Change the first element to 'apple'
myArray[0] = 'apple';
console.log(myArray); // Output: ['apple', 2, 3, 4, 5]The length property of an array returns the number of elements it contains:
console.log(myArray.length); // Output: 5You can add new elements to an array using the push() method:
// Add 'banana' to the end of the array
myArray.push('banana');
console.log(myArray); // Output: ['apple', 2, 3, 4, 5, 'banana']To remove an element from an array, you can use the splice() method. Here's how to remove the first element:
// Remove the first element
myArray.splice(0, 1);
console.log(myArray); // Output: [2, 3, 4, 5, 'banana']Multidimensional arrays are arrays within arrays. They're useful for organizing complex data structures:
// Declare a multidimensional array
const myArray2D = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(myArray2D[1][1]); // Output: 5JavaScript provides several useful methods for arrays. Here are a few examples:
indexOf(): Finds the index of a specific value in the arrayincludes(): Checks if the array includes a specific valueforEach(): Iterates through each element in the arraymap(): Creates a new array with the results of calling a provided function on every element in the arrayfilter(): Creates a new array with all elements that pass the test provided by a functionreduce(): Reduces the array to a single value by repeatedly applying a function to each elementWhat is the output of `console.log(myArray[0]);` in the first example?
This is just the beginning of our JS Arrays lesson. In the following sections, we'll dive deeper into array methods and explore real-world examples. Stay tuned! 🚀