JavaScript: Arrays

Declaring Array

Array can be declared using [] or array constructor new Array()
const arrayName = [item1, item1, item1];
Using constructor new Array() is resulting exactly same thing (well, not really*). Therefore unnecessary. It's just reduce simplicity, readability, and execution speed.
const arrayName = new Array(item1, item1, item1);
* When the array only have 1 element and it happened to be a number, it can't be created using new Array() constructor, because that's the same with syntax to make an array with x number of elements.
const animals = new Array("Horse");
animals;        // (1) ["Horse"]

const numbers = new Array(3);
numbers;        // (3) [empty x 3]

Constant Array

Array is usually declared as a constant.
const names = ["Adam", "Ben", "Chris"];
names = ["Don", "Edward", "Frank"];     // Error
Elements can be reasigned.
What's constant here is the reference to an array. It doesn't mean we can't change the elements of the array.
names[1] = "Beth";      // Change an element
names.push("Don")       // Add an element
Spaces and line breaks are not important
const names = [
    "Adam",
    "Ben",
    "Chris"
];
Const: Assigned when declared.
Declaring with const, variable have to be initialized when declared. Using const without initializing results in a syntax error.
const names;
names = ["Adam", "Ben", "Chris"];       // Doesn't work
What need to be declared is the fact it is an array.
It can be empty and filled later on.
const names = [];
names[0] = "Adam";
names[1] = "Ben";
names[2] = "Chris";
With var
Meawhile while declaring with var, we can even assign the value prior to being declared.
names = ["Adam", "Ben", "Chris"];
var names;                              // Works

Constant Arrays have Block Scopes

Const block scope
Array declared with const has a block scope. 2 arrays with the same name, outside and inside a block, are not the same.
const names = ["Adam", "Ben", "Chris"];
alert (names[0]);       // "Adam"

{
    const names = ["Don", "Edward", "Frank"];
    alert (names[0]);   // "Don"
}

alert (names[0]);       // "Adam"
Array declared with var doesn't have a block scope.
var names = ["Adam", "Ben", "Chris"];
alert (names[0]);       // "Adam"

{
    var names = ["Don", "Edward", "Frank"];
    alert (names[0]);   // "Don"
}

alert (names[0]);       // "Don"
Redeclaring an array with const vs var
Redeclaring an array with const is only allowed in different scope/block.
{
    const names = ["Adam", "Ben", "Chris"]; 
    const names = ["Adam", "Ben", "Chris"];     // Not allowed
}
const names = ["Adam", "Ben", "Chris"];         // Allowed
const names = ["Adam", "Ben", "Chris"];         // Not allowed

{
    const names = ["Adam", "Ben", "Chris"];     // Allowed
}
Redeclaring and reassigning an array with var is allowed anywhere.
var names = ["Adam", "Ben", "Chris"];
var names = ["Adam", "Ben", "Chris"];       // Allowed
names = ["Adam", "Ben", "Chris"];           // Allowed
Redeclaring an array previously declared with var and now with const not allowed.
var names = ["Adam", "Ben", "Chris"];
const names = ["Adam", "Ben", "Chris"];         // Not allowed

{
    var names = ["Adam", "Ben", "Chris"];       // Allowed
    const names = ["Adam", "Ben", "Chris"];     // Not allowed
}
Redeclaring an array previously declared with const and now with var not allowed.
const names = ["Adam", "Ben", "Chris"];
const names = ["Adam", "Ben", "Chris"];     // Not allowed
var names = ["Adam", "Ben", "Chris"];       // Not allowed
names = ["Adam", "Ben", "Chris"];           // Not allowed

{
    const names = ["Adam", "Ben", "Chris"];     // Allowed
    const names = ["Adam", "Ben", "Chris"];     // Not allowed
    var names = ["Adam", "Ben", "Chris"];       // Not allowed
    names = ["Adam", "Ben", "Chris"];           // Not allowed
}

Arrays vs Objects

Array is a special type of object
typeof of an array will return "object". But still, arrays are best described as arrays.
const names = ["Adam", "Ben", "Chris"];
typeof names;       // "object"
Arrays vs typical objects
Arrays are special kind of object with numbered indexes.
  • Arrays use "numbered indexes" to access its "elements".
  • Objects use "named indexes" to access its "members"
const personArr = ["John", "Doe", 46];
personArr[0];           // "John"

const personObj = {firstName: "John", lastName: "Doe", age: 46};
personObj.firstName;    // "John"
Array elements can be objects
They can be objects, they can be arrays, they can even be functions.
const myArray = [];
myArray[0] = Date.now;      // 
myArray[1] = myFunction;
myArray[2] = myCars;

Identifying Array

typeof
It's not very informative since the result is just "object"
typeof arrayName;
// "object"
Array.isArray() method
Array.isArray(arrayName);
// true
instanceof Array
arrayName instanceof Array;
// true

Array Properties and Methods

Built-in array properties and methods
myArray.length      // Length property: returns the number of elements
myArray.sort()      // Sort method: sorts the array

Accessing Array Elements

Accessing first and last elements
const names = ["Adam", "Ben", "Chris"];
names[0];               // First element, "Adam"
names[names.length-1]   // Last element, "Chris"
Looping elements with for loop
Using for loop to create html listing ul listing of the array.
const names = ["Adam", "Ben", "Chris"];

let list = "<ul>";
for (let i = 0; i < names.length; i++) {
    list += "<li>" + names[i] + "</li>";
}
list += "</ul>";

list;
// '<ul><li>Adam</li><li>Ben</li><li>Chris</li></ul>' 
  • Adam
  • Ben
  • Chris

forEach

Looping elements with myArray.forEach() function
const names = ["Adam", "Ben", "Chris"];

let list = "<ul>";
names.forEach(myFunction);
list += "</ul>";

function myFunction(value) {
    list += "<li>" + value + "</li>";
}

list;
// '<ul><li>Adam</li><li>Ben</li><li>Chris</li></ul>' 
  • Adam
  • Ben
  • Chris
Adding elements with push() method
It's adding at the end of the array.
const names = ["Adam", "Ben", "Chris"];
names.push("Don");

names;      // (4) ['Adam', 'Ben', 'Chris', 'Don']
Adding elements using length property
It's adding at the end of the array.
const names = ["Adam", "Ben", "Chris"];
names[names.length] = "Don";

names;      // (4) ['Adam', 'Ben', 'Chris', 'Don']
Associative arrays / hashes: Arrays with named indexes
Many programming languages support arrays with "named indexes". JavaScript doesn't. In JavaScript, arrays always use "numbered indexes".
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person;             // (3) ['John', 'Doe', 46]
person.length;      // 3
person[0];          // "John"
If we assign named indexes to an array, JavaScript will redefine the array to an object. After that, some array methods and properties will not produced same result as before.
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person;             // [firstName: 'John', lastName: 'Doe', age: 46]
person.length;      // 0
person[0];          // undefined

References