𝗔𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
An array is an object used to store collections of data.
Instead of creating separate variables for every item, you use one array to hold them all. This saves time and makes your code clean.
Key features of JavaScript arrays:
- Elements: These are the values inside your list.
- Ordered: Every element has a specific position.
- Zero indexed: The first item sits at index 0. The second item sits at index 1.
- Dynamic size: You can add or remove items whenever you need.
- Heterogeneous: You can store numbers, strings, objects, or even other arrays in one list.
Why use them?
If you have 300 car names, you cannot create 300 separate variables. An array holds all 300 names under one name. You then find any car using its index number.
How to create an array:
The best way is using an array literal. It is fast and easy to read.
const cars = ["Saab", "Volvo", "BMW"];
You can also use the new keyword, but it is not necessary. Stick to the literal method for better performance.
Important facts:
- Arrays are objects. The typeof operator returns "object" when you check an array.
- You can store anything inside an array. This includes functions and other objects.
- The length property tells you how many items are in your list.
- The length is always one higher than the highest index.
Accessing data:
To get the first item: let first = fruits[0];
To get the last item: let last = fruits[fruits.length - 1];
Source: https://www.w3schools.com/js/js_arrays.asp
Full post: https://dev.to/madhanraj/arrays-in-javascript-56e1