Arrays in JavaScript


 Arrays

Arrays allow us to store several different values in a single variable.

For example, let us say that we have a grocery list. We can't be creating new variables for each item, right?

Declaration

There are two ways to create a empty array:
let array = [];
let array = new Array();
Almost always, developers use the first way.
We can supply initial elements in brackets:
let array = ["Apple", "Banana", "Orange"];
Array elements are properly ordered and numbered, starting from zero.
We can get a element by its number:
let array = ["Apple", "Banana", "Orange"];

console.log( array[0] ); // Apple
console.log( array[1] ); // Banana
console.log( array[2] ); // Orange
We can also replace a element:
let array[0] = "Pear";
let array[1] = "Tomato";
let array[2] = "Plum";


Or add a new one in the array:
array[3] = "Lemon";

We can also use alert() or console.log() to show the whole array.
let array = ["Apple", "Banana", "Orange"];

console.log( array );
alert( array );
An array can store any kind of elements.

For example:
// mix of values
let array = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];

// get the object at index 1 and then show its name
alert( array[1].name ); // John

// get the function at index 3 and run it
array[3](); // hello

An array may have a trailing comma.
let array = [
        "Apple",
        "Banana",
        "Orange",
];

Post a Comment

Previous Post Next Post