Js Arrays
Js Arrays
Arrays
Arrays
• An array is a special variable, which can hold
more than one value
• An array can hold many values under a single
name, and you can access the values by
referring to an index number.
• Syntax
• const array_name = [item1, item2, ...];
Examples
• const cars = [
"Saab",
"Volvo",
"BMW"
];
• const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
• const cars = new Array("Saab", "Volvo", "BMW");
There is no need to use new Array().
For simplicity, readability and execution speed, use the array literal
method.
Index
• Array indexes start with 0.
• [0] is the first element. [1] is the second element.
• Example
• const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
0 -> Saab = car[0]
1 -> volvo= car[1]
2-> BMV=ca[2]
Changing Value
• To change element Value , we use index
property
• Example:
• car[0]=“Tata” , car[1]=“maruti”;
• To change the full array we can accessed by
referring to the array name
• Example
• document.write(cars);
Arrays are Objects
• Arrays are a special type of objects. The typeof operator
in JavaScript returns "object" for arrays.
• As JS arrays are heterogeneous.
• can have variables of different types in the same Array.
Also,can have functions in an Array as well as can have
arrays in an Array
• Example: const person = ["John", "Doe", 46];
• Different
• Arrays use numbers to access its "elements".
• Objects use names to access its "members".
The length Property