If you're learning JavaScript, understanding arrays is non-negotiable. Theyβre everywhere β storing data, managing lists, or manipulating collections. In this guide, we're going full code-mode π» to explore how arrays work.
No fluff, just code. Letβs go π
π¦ Creating Arrays
const fruits = ["apple", "banana", "mango"];
const numbers = [1, 2, 3, 4];
const colors = new Array("red", "green", "blue");
Arrays can hold any data type β strings, numbers, even objects or other arrays.
π Accessing Elements
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "mango"
Arrays use zero-based indexing, meaning the first element is at index 0.
fruits[1] = "orange";
console.log(fruits); // ["apple", "orange", "mango"]
βοΈ Array Methods in Action
fruits.push("grape"); // Add to end
fruits.pop(); // Remove from end
fruits.shift(); // Remove from start
fruits.unshift("kiwi"); // Add to start
fruits.splice(1, 0, "pineapple"); // Insert at index 1
These methods help you add/remove elements from different positions in the array.
π Looping Through Arrays
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
fruits.forEach(fruit => {
console.log(fruit);
});
Looping helps you perform actions on each element. forEach is cleaner and more modern.
π§ Destructuring Arrays
const [first, second] = fruits;
console.log(first); // "apple"
console.log(second); // "orange"
Destructuring lets you pull out values easily without accessing them one-by-one.
β
Wrap Up
Arrays are powerful and versatile. Mastering just these few concepts can take you a long way. Practice these snippets, build your own mini-projects, and youβll see arrays in a whole new light! π
Got a favorite array method or a cool trick? Share it in the comments!
Top comments (2)
love smashing arrays together, never gets old honestly - you think learning basic stuff like this early on actually changes how you tackle bigger projects later or nah
Totally agree β array manipulation is such a core part of JS, and yeah, learning the basics early absolutely shapes how you think later. When you understand things like how data flows or how to structure logic with arrays/objects, it makes tackling more complex features way less intimidating. It's like building muscle memory for code.