DEV Community

Cover image for πŸ”₯ JavaScript Arrays Explained with Practical Code Examples
Shifa
Shifa

Posted on

πŸ”₯ JavaScript Arrays Explained with Practical Code Examples

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.
Enter fullscreen mode Exit fullscreen mode

πŸ” Accessing Elements

console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "mango"
Enter fullscreen mode Exit fullscreen mode

Arrays use zero-based indexing, meaning the first element is at index 0.

fruits[1] = "orange";
console.log(fruits); // ["apple", "orange", "mango"]
Enter fullscreen mode Exit fullscreen mode

βš™οΈ 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
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
nevodavid profile image
Nevo David

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

Collapse
 
shifa_2 profile image
Shifa

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.