We have learned that a variable can hold only one value, for example var i="value", we can assign only one literal value to i. We cannot assign multiple literal values to a variable i. To overcome this problem, JavaScript provides an array.
◾An array is a special type of variable, which can store multiple values using special syntax. Every value is associated with numeric index starting with 0.
◾Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor syntax.
◽Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in square brackets.
const superheroes = ['iron man','spiderman','dhillon']
console.log(superheroes);
//get value from specific position
console.log(superheroes[0]);
console.log(superheroes[1]);
console.log(superheroes[2]);
◽Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
//declare array with new keyword
var superheroes = new Array();
superheroes[0] = "iron man";
superheroes[1] = "spiderman";
superheroes[2] = "thor";
console.log(superheroes); //assigning value to array index
0 Comments