Imagine you want to store a list of your favorite fruits, exam marks, or daily tasks. You could create separate variables for each one, but that becomes messy very quickly. Arrays solve this problem by letting you store multiple values together in a single variable.
In JavaScript, an array is an ordered collection of values. That means every item has a position, and we can access items using that position number, called an index.
1. What Arrays Are and Why We Need Them
An array stores multiple values in order inside one variable.
The code above works, but it is not very practical when the list gets longer.
This is easier to manage because all related values are grouped together in one place.
2. How to Create an Array
You create an array using square brackets [ ] and separate items with commas.
Arrays can hold strings, numbers, booleans, and more. For beginners, just remember that an array is a collection of values stored in order.
3. Accessing Elements Using Index
Every value in an array has an index, and indexing starts from 0, not 1.
This means:
- first element is at index
0 - second element is at index
1 - third element is at index
2
4. Updating Elements
You can change an array value by using its index.
Here, the value at index 1 changed from "Banana" to "Orange".
5. Array length Property
The length property tells you how many elements are in the array.
This is very useful when looping through arrays or finding the last element.
6. Basic Looping Over Arrays
A simple way to print all elements of an array is using a for loop.
Step by step:
i = 0starts at the first elementi < fruits.lengthkeeps the loop inside array boundariesi++moves to the next index each time
This prints every value in order.
7. Practice Assignment
Try this in your browser console:
This assignment helps you practice:
- creating an array
- accessing the first and last element
- changing one value
- looping through all elements
Conclusion
Arrays are one of the most useful basics in JavaScript. They let you store multiple values in one place, access them using indexes, update values when needed, check length, and loop through the whole collection.
Keep the mental model simple: an array is an ordered list of values, and indexing starts from 0. Once this becomes natural, working with JavaScript data gets much easier.