DEV Community

Megalraja
Megalraja

Posted on

JavaScript Arrays — More Than Just a List

When I started learning JavaScript, one thing I kept seeing everywhere was arrays.

But the simple question is: Why do we even need them?

Imagine storing the names of three students:

let student1 = "Arun";
let student2 = "Bala";
let student3 = "Kiran";
Enter fullscreen mode Exit fullscreen mode

This works, but imagine having 100 students.

That's where an array becomes useful:

let students = ["Arun", "Bala", "Kiran"];
Enter fullscreen mode Exit fullscreen mode

Now all the names are stored together, and we can access them using their index:

console.log(students[0]); // Arun
console.log(students[2]); // Kiran
Enter fullscreen mode Exit fullscreen mode

Arrays are Objects in JavaScript

Here's an interesting part:

let numbers = [10, 20, 30];

console.log(typeof numbers);
// "object"
Enter fullscreen mode Exit fullscreen mode

That's because an array is a special type of object in JavaScript.

But arrays are designed specifically for ordered data, which is why we get features like indexes and methods such as push() and pop().

Heterogeneous Data

Another interesting thing about JavaScript arrays is that they can hold different types of values:

let data = [10, "Hello", true, 25.5, null];
Enter fullscreen mode Exit fullscreen mode

This is called a heterogeneous array because different data types can exist in the same array.

We can also easily add or remove elements:

students.push("David"); // Add
students.pop();         // Remove
Enter fullscreen mode Exit fullscreen mode

So, the basic idea is:

Array → Special type of object

Purpose → Store ordered collections of values

Index → Access a particular value

Heterogeneous → Different data types can exist together

push() → Add an element

pop() → Remove an element

Arrays look simple at first, but understanding why they're objects and how they're different from normal objects makes the JavaScript data-type concept much clearer.

What surprised you most about JavaScript arrays?

Top comments (0)