Arrays in JavaScript

Our first example demonstrates the use of arrays in JavaScript. In JavaScript, an array is a versatile data structure that can hold multiple values of different types.

// Here we create an array 'a' that will hold exactly 5 elements.
// In JavaScript, arrays are zero-indexed and can dynamically change in size.
let a = new Array(5);
console.log("emp:", a);

// We can set a value at an index using the
// array[index] = value syntax, and get a value with
// array[index].
a[4] = 100;
console.log("set:", a);
console.log("get:", a[4]);

// The length property returns the length of an array.
console.log("len:", a.length);

// Use this syntax to declare and initialize an array
// in one line.
let b = [1, 2, 3, 4, 5];
console.log("dcl:", b);

// In JavaScript, we don't need to specify the size of the array
// when initializing it. It will automatically adjust.
b = [1, 2, 3, 4, 5];
console.log("dcl:", b);

// JavaScript doesn't have a direct equivalent to Go's index-based
// initialization. However, we can achieve a similar result like this:
b = [100, , , 400, 500];
console.log("idx:", b);

// Array types are one-dimensional, but you can
// create multi-dimensional arrays by nesting arrays.
let twoD = Array(2).fill().map(() => Array(3).fill(0));
for (let i = 0; i < 2; i++) {
    for (let j = 0; j < 3; j++) {
        twoD[i][j] = i + j;
    }
}
console.log("2d: ", twoD);

// You can create and initialize multi-dimensional
// arrays at once too.
twoD = [
    [1, 2, 3],
    [1, 2, 3],
];
console.log("2d: ", twoD);

When we run this script, we’ll see the following output:

emp: [ <5 empty items> ]
set: [ <4 empty items>, 100 ]
get: 100
len: 5
dcl: [ 1, 2, 3, 4, 5 ]
dcl: [ 1, 2, 3, 4, 5 ]
idx: [ 100, <2 empty items>, 400, 500 ]
2d:  [ [ 0, 1, 2 ], [ 1, 2, 3 ] ]
2d:  [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]

Note that arrays in JavaScript are more flexible than in some other languages. They can change in size dynamically and can hold elements of different types. The console.log function is used to print the arrays, which displays them in a similar format to the original example.