Introduction to Array
Explore arrays in JavaScript to understand how they store multiple related values in contiguous memory locations. Learn about array properties like fixed size and indexing, and see real-world examples of their use in programming to manage data effectively.
When writing programs, we often need to store a group of related values. Individual variables can only hold one value at a time, which makes them a poor fit for this kind of task. To see why, consider a simple example.
Why do we need an array?
Imagine you just finished a 10-game bowling tournament, and you want to jot down your score from each game. You could create ten separate pieces of paper, one for each score.
But these separate pages would be chaotic to manage. The same problem occurs in programming. To store ten scores, you would have to create ten separate variables, ten separate names to remember, and no easy way to loop through them.
The code would become unworkable as the number of scores grows. This is the core limitation of primitive variables: they can only hold one value at a time, so managing a collection of related values with them quickly becomes impractical.
This problem isn’t unique to bowling scores. Consider the following examples:
In gaming, leaderboards need to store and rank multiple player scores in order.
In data logging, a weather station records temperature every hour throughout the day.
In image processing, every pixel on our screen has a position and a color value that must be tracked.
What all of these share is the same underlying need: store a collection of related values and access any one of them quickly by its position. Individual variables alone cannot do this efficiently.
What is the solution? To derive the solution, consider the bowling game example. Instead of creating ten cards to store the results of individual games, a single scorecard with ten indexed slots is used.
In programming, this scorecard is called an array.
What is an array?
By definition, an array stores a collection of elements of the same type in contiguous memory locations.
Think of an array like a row of numbered ...