Think of an array as a box with lots of little compartments. 😄 You can store a piece of data in each compartment.
For example, if you have an array like [1, 2, 3, 4], the values 1, 2, 3, and 4 are called elements.
Each compartment also has a number called an index, and the index always starts from 0.
[1, 2, 3, 4]
0 1 2 3
So, the element at index 0 is 1.
Let's look at another example.
const fruits = ["apple", "orange", "grape"];
If you want to get "apple", you can simply write:
fruits[0]
If you want "grape", you can write:
const myFruit = fruits[2];
console.log(myFruit);
The output will be:
"grape"
🍇
So, when do we use arrays?
Arrays are very useful when you want to store data in order and access each item by its position.
The best part is that JavaScript already provides arrays as a built-in data structure, so you can start using them right away without creating your own.
That's all for today! See you next week 😉
Top comments (0)