JavaScript Arrays 101
Before Arrays existed in programming, you had only 2 chocices: name every variable individually, or give up. Imagine if you have to track the scores of 100 students, you have to write score 1, score 2, score 3 and so on.
Look at the real world, it is full of collections, shopping lists, and song queues. Arrays are the most fundamental way to mirror that reality in memory. Arrays say: these things belong together, they are the same kind of thing, and their order matters.
Core Concepts Of Array.
Contiguous indexed storage: An array is a block of memory where each slot is reachable by its index (the position). You don't navigate to the 5th element by walking through elements 1 to 4. You jump directly. This is called O(1) random access constant time regardless of array size.
Zero based indexing: you may think that in array the first element index is 1, but the array is 0 index based. First element index will be 0, and this is a design choice inherited from C.
JavaScript arrays are objects: The type of arrays in JavaScript is an object. It is a special kind of object with numeric string keys and a length property
Length as a derived property: The length of an array is not stored as a count you manually maintain. JavaScript derives it (or maintains it internally) as the highest index + 1
Let's create an Array and understand it
const arr = ['Iron Man', 'Spider Man', 'Thors', 'Captain America']
Now, let's say you have to select the 2nd hero from an array. How do you access that?
You can simply access array elements by their index, look at code
console.log(arr[1]) // Spider Man
how index looks
1st element 'Iron Man' = 0 index
2nd element 'Spider Man' = 1 index
3rd element 'Thors' = 2 index
4th element 'Captain America' = 3 index
Now you may be thinking that I can create an array, access its elements, and update it, but how? Yes, you can update array elements
arr[2] = 'Hulk'
console.log(arr) // [ 'Iron Man', 'Spider Man', 'Hulk', 'Captain America' ]
You know how to create an array, access it by index, and you also know how to update it, and you just keep adding your favorite heroes into that, and you forget to count how many heroes you have added, so now you're thinking about how to check the length of the array.
Look at the code:
console.log(arr.length) // 4
Looping over an Array
Can I get each element one by one? You may be thinking that,
Here is the code for looping over an array
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
That's all for today, for arrays, hope you learn something from this and understand arrays better.