JavaScript Arrays

📌 JavaScript Arrays

Last Updated: 10 Feb, 2025

An array in JavaScript is an ordered list of values. Each value is called an element, and each element has a numeric position (index).

✅ Creating Arrays

🔹 1. Using Array Literals

Use square brackets [] to define an array.

// Empty Array
let a = [];
console.log(a);

// Array with values
let b = [10, 20, 30];
console.log(b);

🔹 2. Using the new Keyword

let a = new Array(10, 20, 30);
console.log(a);

Note: The array literal method [] is preferred for efficiency and readability.

🛠️ Basic Operations on Arrays

🔹 1. Accessing Elements

let arr = ["HTML", "CSS", "JS"];
console.log(arr[0]); // HTML
console.log(arr[1]); // CSS

🔹 2. First & Last Element

let fst = arr[0]; // First Element
let lst = arr[arr.length - 1]; // Last Element

🔹 3. Modifying Elements

arr[1] = "Bootstrap"; // Modify CSS to Bootstrap

🔹 4. Adding Elements

arr.push("Node.js"); // Adds to end
arr.unshift("Web Dev"); // Adds to start

🔹 5. Removing Elements

arr.pop(); // Removes last element
arr.shift(); // Removes first element

🔹 6. Array Length

console.log(arr.length);

🔹 7. Iterating Through an Array

Using for Loop:

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Using forEach() Loop:

arr.forEach(x => console.log(x));

🚀 Advanced Array Operations

🔹 1. Concatenating Arrays

let arr1 = ["HTML", "CSS"];
let arr2 = ["JS", "React"];
let combined = arr1.concat(arr2);
console.log(combined);

🔹 2. Converting to String

console.log(arr.toString());

🔹 3. Checking Array Type

console.log(Array.isArray(arr)); // true
console.log(arr instanceof Array); // true

🎯 Common JavaScript Array Problems

✅ Basic Problems

  • Print Alternate Elements
  • Find Largest Element
  • Remove Duplicates
  • Reverse an Array

✅ Medium Problems

  • Sort an Array of 1 to n
  • Reorder According to Index
  • Minimum Swaps to Sort

✅ Hard Problems

  • 4 Sum – Distinct Quadruples
  • Top K Frequent Elements
  • Surpasser Count

🎯 Conclusion

JavaScript arrays are a powerful tool for storing and manipulating data. By mastering these concepts, you can improve your coding skills significantly.

✨ Happy Coding! 🚀

Powered by Blogger.