- Syntax:
const _array_name_ = [_item1_, _item2_, ...];
- For example:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
- JavaScript has a built-in array constructor
new Array()
. But you can safely use []
instead. The new
keyword:const cars = new Array("Saab", "Volvo", "BMW");
- To access element:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
- To change element:
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel"; // Opel,Volvo,BMW
- With JavaScript, the full array can be accessed by referring to the array name:
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars; // 'demo' is the id
- Arrays are a special type of objects. The
typeof
operator in JavaScript returns "object" for arrays. Arrays use numbers to access its "elements":const person = ["John", "Doe", 46];
person[0] // returns John
Whereas Objects use names to access its "members":const person = {firstName:"John", lastName:"Doe", age:46};
person.firstName // returns John
- You can have variables of different types in the same Array.You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array.
- JavaScript does not support arrays with named indexes. Always use numbered indexes.