4. JavaScript Arrays

Taniya Gupta
8 min readJan 11, 2023
Image Credits : Wikimedia Commons. (Edited as Creative Liberty)

Another useful type in JavaScript is Arrays. Dive Deep into this article to know about JavaScript Arrays, how they work, sparse arrays & Few Useful Array Methods.

Introduction to JavaScript Arrays

Arrays in JavaScript are just containers, which can hold value for any type, whether it be string, number, object or even a another array (Multidimensional Array). Arrays hold these values in numerically indexed positions.

Key Points about JavaScript Arrays:

  1. Arrays are basically special objects. They can have properties of their own.
  2. They are 0-indexed.
  3. They are resizable and can contain a mix of different data types.
  4. JavaScript array-copy operations create shallow copies.
var arr = [
"Hi there! I am a JavaScript Developer",
1000,
true
];

arr[0]; // Hi there! I am a JavaScript Developer"
arr[1]; // 1000
arr[2]; // true

console.log(arr.length); // 3

console.log(typeof arr); // object

If we see theoretically, we can use array as a normal object with own named properties, or we can use an object as array by only giving it numerical properties. But this would be an inappropriate & improper usage.

💡 Tip : Use arrays for numerically positioned values and use objects for named properties. (i.e in Arrays, Index should be numbers. For other than number indexes, use objects.)

In JavaScript, we don’t need to declare the size of the array at time of declaring the array (Pre-Size). We can just declare them & add values.

var arr = [ ];

console.log(arr.length); // 0

arr[0] = 1;
arr[1] = "2";
arr[2] = [ 3 ];

console.log(arr.length); // 3

Sparse Array

Array with at least one “empty slot” in it is called a “sparse array.” We should be careful about creating sparse arrays (i.e leaving or creating empty or missing slots).

var arr = [ ];

arr[0] = 1;
// no `arr[1]` slot set here
arr[2] = [ 3 ];

console.log(arr[1]); // undefined

console.log(a.length); // 3

Although the above thing works, but it can lead to confusing behavior with the empty slots. However, slot appears to have undefined value, but if we explicitly set (a[1] = undefined), then its behaviour will not be same as this case.

Array( ) Constructor

  1. Array Constructor used with new keyword or without it are same only. i.e. Array(1,2,3) is the same outcome as new Array(1,2,3).
  2. It has a special form. i.e If only one number argument is passed, then instead of providing that value as contents of array, it's taken as a length to "presize the array" by the JS engine.
  3. In Actual, Presizing is nothing, but instead, we are creating an empty array, of that length (i.e number value specified).
  4. To initialize an array with a single element and if that element is a number, we should use bracket [], otherwise it would be taken as length as stated above.

Browser developer consoles vary on how they represent such kind of array, Let’s see how this works in different Browsers:

var a = new Array( 3 );
var b = [ undefined, undefined, undefined ];
var c = [];
c.length = 3;

console.log(a); // [empty × 3]
console.log(b); // [ undefined, undefined, undefined ]
console.log(c); // []

----------------------------------------------------------------
delete b[1]; //Deleting element at index 1 of the array
console.log(b); // [undefined, empty, undefined]

----------------------------------------------------------------
var arr = [3]; // creates array with single element 3

In Chrome :

Consider above code,

a in Chrome (at time of writing):[ undefined x 3 ]. It implies, there are three undefined values in slots of this array, whereas, in fact no slots exist.

With c, empty slots in array can even happen after creation of array. While changing the length of array, we may implicitly introduce empty slots.

If we call delete b[1]it would introduce an empty slot into middle of b. 💡💡Notice, how [undefined, undefined, undefined] output changed to [undefined, empty, undefined] .

In Firefox:

In Firefox, at time of writing, Firefox reports [ , , , ] for a and c . Three commas implies four slots. (Wondering, from where this 4th slot came?)

Firefox puts an extra , on end because as of ES5, trailing commas in lists (array values, property lists, etc.) are allowed.

Array Methods

  1. concat() — joins two or more arrays & returns a new array.
//-------------Concat----------
var arr = ['Foo', 'Bar', 'Game'];
arr = arr.concat('10', '20', '30');
console.log(arr); //['Foo', 'Bar', 'Game', '10', '20', '30']

2.join() — joins all elements of array into a string.

//-------------Join----------
var arr = ['Foo', 'Bar', 'Game'];
arr = arr.join(' - ');
console.log(arr); // Foo - Bar - Game

3.push() — adds one or more elements to end of array & returns resulting length of array.

//-------------Push----------
var arr = ['Foo', 'Bar', 'Game'];
var y = arr.push('Baz');
console.log(arr); // ['Foo', 'Bar', 'Game', 'Baz']
console.log(y); // 4

4.pop() — removes last element from array & returns it.

//-------------Pop----------
var arr = ['Foo', 'Bar', 'Game'];
var x = arr.pop();
console.log(arr); // ['Foo', 'Bar']
console.log(x); // Game

5. shift() — removes first element from array & returns it.

//-------------Shift----------
var arr = ['Foo', 'Bar', 'Game'];
var x = arr.shift();
console.log(arr); // ['Bar', 'Game']
console.log(x); // Foo

6. unshift() — adds one or more elements to front of array & returns new length of array.

//-------------UnShift----------

var arr = ['Foo', 'Bar', 'Game'];
var y = arr.unshift('Baz', 'Box');
console.log(arr); // ['Baz', 'Box', 'Foo', 'Bar', 'Game']
console.log(y); // 5

7.slice() — extracts section of array & returns new array.

//-------------Slice----------
var arr = ['Baz', 'Box', 'Foo', 'Bar', 'Game'];
arr = arr.slice(1, 4);
console.log(arr); // ['Box', 'Foo', 'Bar']

8.at() — returns element at specified index in array, or undefined if index is out of range.

//-------------At----------
var arr = ['Baz', 'Box', 'Foo', 'Bar', 'Game'];
console.log(arr.at(-2)); // Bar

9.splice() — removes elements from an array & (optionally) replaces them. It returns items, removed from array.

//-------------Splice----------
var arr = ['Baz', 'Box', 'Foo', 'Bar', 'Game'];
arr.splice(1, 3, 'I', 'Like', 'This');
console.log(arr); // ['Baz', 'I', 'Like', 'This', 'Game']

10.reverse() — reverse elements of the array & returns a reference to the array.

//-------------Reverse---------
var arr = ['Baz', 'Box', 'Foo', 'Bar', 'Game'];
arr.reverse(); // ['Game', 'Bar', 'Foo', 'Box', 'Baz']

11.flat() — returns new array with all sub-array elements concatenated into it recursively up to specified depth.

//---------Flat------------------
var arr = ['Baz', 'Box', ['Foo', 'Bar'],['Apt', 'Game']];
arr = arr.flat();
console.log(arr); // ['Baz', 'Box', 'Foo', 'Bar', 'Apt', 'Game']

12.sort() — sorts elements of array in place & returns a reference to the array.

//-------------Sort----------
var arr = ['Foo', 'Bar', 'Game', 'Baz', 'Box'];
arr.sort();
console.log(arr); // ['Bar', 'Baz', 'Box', 'Foo', 'Game']

13.indexOf() — searches array for ‘searchelement’ & returns the index of first match.

//-------------Indexof----------
var arr = ['Foo', 'Bar', 'Game', 'Baz', 'Box'];
console.log(arr.indexOf('Baz')); // 3

14.lastIndexOf() — works like indexOf, but starts at end & searches backwards.

//-------------LastIndexof----------

var arr = ['Foo', 'Bar', 'Game', 'Baz', 'Box', 'Foo'];

console.log(arr.lastIndexOf('Foo')); // 5

// starting to find from index 3 searching backward
console.log(arr.lastIndexOf('Foo', 3)); // 0

console.log(arr.lastIndexOf('Ape')); // -1

15.forEach() — It is an iterative method, that executes callback on every array item and returns undefined.

//-------------ForEach----------
var arr = ['Foo', 'Bar', 'Game'];
arr.forEach((element) => {
console.log(element);
});

// Foo
// Bar
// Game

16.map() — returns a new array of return value from executing callback on every array item.

//-------------Map-----------
var arr = ['foo', 'bar', 'game'];
var arr1 = arr.map((item) => item.toUpperCase());
console.log(arr1); // ['FOO', 'BAR', 'GAME']

17.flatMap() — runs map() followed by a flat() of depth 1.

//-------------flatMap----------
var arr = ['foo', 'bar', 'game'];
var arr1 = arr.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]);
console.log(arr1); // ['FOO', 'foo', 'BAR', 'bar', 'GAME', 'game']

18.filter() — returns a new array containing the items for which callback returned true.

//-------------Filter---------
var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];
arr1 = arr.filter((item) => typeof item === 'number');
console.log(arr1); // [10, 20, 30]

arr2 = arr.filter((item) => typeof item === 'string');
console.log(arr2); // ['Foo', 'Bar', 'Game']

19.find() — returns first item for which callback returned true.

//-------------Find----------
var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];

var a = arr.find((item) => typeof item === 'number');
console.log(a); // 10

var a = arr.find((item) => typeof item === 'string');
console.log(a); // Foo

20.findLast() — returns last item for which callback returned true.

//-------------FidLast----------
var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];

var a = arr.findLast((item) => typeof item === 'number');
console.log(a); // 30

var a = arr.findLast((item) => typeof item === 'string');
console.log(a); // Game

21.findIndex() — returns index of first item for which callback returned true.

//-------------findIndex----------
var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];

var a = arr.findIndex((item) => typeof item === 'number');
console.log(a); // 1

var a = arr.findIndex((item) => typeof item === 'string');
console.log(a); // 0

22.findLastIndex() — returns index of last item for which callback returned true.

//-------------findlastindex----------
var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];

var a = arr.findLastIndex((item) => typeof item === 'number');
console.log(a); // 5

var a = arr.findLastIndex((item) => typeof item === 'string');
console.log(a); // 4

23.every() — returns true if callback returns true for every item in array.

// simple function that checks if given value is a number.
// === is the strict equality operator in JavaScript which checks:
// whether its two operands are equal & returns a Boolean result. (True or False)

function isNumber(value) {
return typeof value === 'number';
}

var arr = [10, 20, 30, 40];
console.log(arr.every(isNumber)); // true

var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];
console.log(arr.every(isNumber)); // false

24.some() — returns true if callback returns true for at least one item in the array.

// simple function that checks if given value is a number.
// === is the strict equality operator in JavaScript which checks:
// whether its two operands are equal & returns a Boolean result. (True or False)

function isNumber(value) {
return typeof value === 'number';
}

var arr = [10, 20, 30, 40];
console.log(arr.some(isNumber)); // true

var arr = ['Foo', 10, 'Bar', 20, 'Game', 30];
console.log(arr.some(isNumber)); // true

var arr = ['Foo', 'Bar', 'Game','Baz'];
console.log(arr.some(isNumber)); // false

25.reduce() — applies callback(accumulator, currentValue, currentIndex, array) for each value in array for purpose of reducing the list of items down to a single value. It returns final value returned by callback function.

//-------------Reduce----------

var arr = [10, 20, 30];
var total = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(total); // 60

26.reduceRight() — works like reduce(), but starts with last element.

//-------------ReduceRight----------

var arr = [10, 20, 30];
var total = arr.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(total); // 60

Console.log is used for demonstration purpose in the article, however it should be avoided in the production code.

Happy JavaScript Learning & Coding!😀

Thanks for reading :) That’s it, I hope you liked the article.

Who am I to write?

Just a curious Learner, who loves to develop websites, and have developed few websites using various templates, using React (from scratch) as well, most of them as personal projects or college club sites, since past 3–4 years. In short, I have worked on React, JavaScript, CSS & HTML and still learning new things daily!

Feel free to reach out to me, if you want to discuss anything related.

I would be glad & happy if you send your valuable feedback & suggestions. Your suggestions really matter!!

You can contact me here -
LinkedIn: https://www.linkedin.com/in/itaniyagupta/

Previous Articles in the the series, access below👉 :

1. Introduction to JavaScript — https://medium.com/@itaniyagupta/1-introduction-to-javascript-b518204f1fa6

2. JavaScript Values & Types — https://medium.com/@itaniyagupta/2-javascript-values-types-8aad10feebfb

3. JavaScript Objects — https://itaniyagupta.medium.com/3-javascript-objects-5b2c66441405

--

--