Array is a set of similar values stored in a contiguous memory location. Array values are accessed by its index. Array index always starts with 0.
Arrays are object in javascript.
Why to use Arrays
Variable in javascript, holds single value at a time, assigning new value overwrites the old values, means old values are not preserved by variables. Hence to store multiple values of similar kind or type, arrays are used.
<script>
let a = 20;
a = 40;
document.write(a);
</script>
In above example, variable a holds value 20 initially, in next statement variable a is assigned a new value 40, and now old value 20 is overwritten by 40.
var num = [20,30,40,33,21,54];
In above example, variable num is an array and holds multiple numbers.
Create an array
Syntax
var name_of_array = ["array_item1","array_item2","array_item3"];
Example
var arr_companies = ["Apple","Microsoft","IBM","Google"];
Create an array with an array literal ‘[]’
[] it is an array literal, creates an empty array.
var name = []; // creates an empty array
Array literal with value
<script>
var name = ["Jack","Jill"];
</script>
Above example, creates an array with two string values. you can add more values as requirement.
Create an array with new keyword
Array can be created with Array() is with new keyword.
<script>
var emp_name = new Array();
</script>
Add elements using array index
Array index starts with 0 and ends with n-1, where n is maximum number of elements – 1.
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
</script>
Array emp_name indexes can be used to store values start with 0.
Access elements of an array
Array elements are accessed by its index.
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
document.write(emp_name[1]);
</script>
Access All array elements
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
document.write(emp_name);
var greetings = ["Hello", "Hi"];
document.write(greetings);
</script>
Get the Length of an array
length property of javascript array returns the number of elements stored in a given array.
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
document.write(emp_name.length);
</script>
Sort an array
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
document.write(emp_name.length);
</script>
Access array elements with Loop
<script>
var emp_name = new Array();
emp_name[0] = "Jack";
emp_name[1] = "Jill";
var str = '';
var arr_len = emp_name.length;
for(i=0; i < arr_len; i = i + 1)
str = str + emp_name [i] + ", ";
document.write(str);
</script>
How to know a variable is an array in javascript
<script>
var name1 = [];
name1[0] = "Jack";
name1[1] = "Jill";
document.write(Array.isArray(name1)); // Return true if a variable is an array
// Do not use typeof because array is an object & it returns Object for an array.
</script>