Welcome to our deep dive into Data Structures and Algorithms! Today, we're going to explore one of the fundamental concepts - Arrays. Let's embark on this exciting journey together! š
An array is a data structure that stores a collection of elements, each of which can be of the same type. Think of it as a container with compartments, where each compartment holds one item.
// Declaring an array
let myArray = [];To create an array, we first initialize it as a container, and then we can add elements to it using square brackets [].
// Creating an array and adding elements
let myArray = ["Apple", "Banana", "Cherry"];
// Accessing elements
console.log(myArray[0]); // Output: AppleIn JavaScript, arrays can contain different types of elements, such as numbers, strings, or even other arrays!
let mixedArray = [1, "Two", 3.14, ["Nestled", "Arrays"]];We can manipulate arrays by adding, removing, or modifying elements.
To add elements to an array, we can use the push() method, which appends an element to the end of the array.
let myArray = ["Apple", "Banana", "Cherry"];
myArray.push("Durian");
console.log(myArray); // Output: ["Apple", "Banana", "Cherry", "Durian"]To remove elements from an array, we can use the pop() method, which removes the last element, or the shift() method, which removes the first element.
let myArray = ["Apple", "Banana", "Cherry", "Durian"];
myArray.pop();
console.log(myArray); // Output: ["Apple", "Banana", "Cherry"]
myArray.shift();
console.log(myArray); // Output: ["Banana", "Cherry"]To modify an element in an array, we can simply assign a new value to the specific index of the array.
let myArray = ["Apple", "Banana", "Cherry"];
myArray[1] = "Blueberry";
console.log(myArray); // Output: ["Apple", "Blueberry", "Cherry"]What is an array in JavaScript?
Next, let's explore how to search and sort arrays! šÆ