JavaScript Array
What is an Array ?
Array is a single variable that is used to store multiple values. Generally an array is list of elements. It’s a collection of data.
Array In JavaScript:
Unlike other programming language JavaScript array is different where most of the languages array is used to store same type of data but in JavaScript array can holds different type of data, values, elements, objects and functions. JavaScript array is dynamic. You don’t need to worry about the length, it extends automatically.
Why we use Array?
To understand the purpose of using array. Let’s see an example.
Suppose you have a company with 10 employees. After a month you have to give them salary. So you need to know the total salary, bonus, max salary and min salary. Now you want a program which is responsible to calculate all these things. You need to keep these 10 values in memory while you perform your calculations using them. Without an array available to you, you would have to create 10 separate variables with unique names. To calculate the total you need to add them one by one.
Here’s what the average calculation would look like in the JavaScript if you were dealing with just 10 values without using array:
Okay it’s considered that you can do that is this way. But what would you do when you have to calculate 100, 1000 or 10000? Are you really going to want to define 10,000 uniquely-named variables? Can you ensure that you use every one of them correctly in your calculations? No, If you had to do this, why would you decide your profession or major as a programmer.
Now, let’s use an array. When you define an array, you have only one name that refers to the entire array, and then you access individual values (elements) within that array by indexing (sub-scripting) into that array. So, if you needed 10 values or 10,000 values, you would still only define one array.
Here’s what the average calculation would look like in the JavaScript if you were dealing with 10,000 values using array:
In this way you can easily dealing with multiple elements of a large number of array.
Type of Array and how to properly access objects in Array?
Type of array is an object. You can access the array index property with dot notation if array contains function or objects.