Array in JavaScript

Array in JavaScript

·

14 min read

An array is one of the most common concepts of Javascript, which gives us a lot of possibilities to work with data stored inside.

Let’s start by listing 3 characters of your favorite anime and storing them in individual variables. It would look like this:

const Naruto1 = "Itachi";
const Naruto2 = "Madara";
const Naruto3 = "Kakashi";

JavaScript doesn’t know that these are associated with each other. It thinks that these are three separate, unrelated pieces of information. A simple fix would be to group them inside of an array!!!

const Naruto = ["Itachi", "Madara", "Kakashi"];

Now, we’ve grouped all of the characters into a single variable that’s pointing to an array named Naruto. But again, What is an array???

An array is a data structure that contains a list of elements that store multiple values in a single variable.

They’re represented by square brackets [ ] with the indexed data inside being separated by commas.

You should know that we can access the information inside of the array by referring to their index numbers. You'll find more about indexing later in this article.

In JavaScript, the array is a special type of Javascript object, If you'll call the typeof operator on your array, it'll return "object".

typeof Naruto;   // It will return "object"

Declaration of an Array

There are two ways to declare an array:

  • With the literal notation [ ]

      const array = [1, 2, 3];
    
  • With the Array() constructor, by using the Javascript keyword “new”

      const array = new Array(1, 2, 3);
    

    Both creating an array with the array literal or the new Array() constructor keyword does the same thing. But people prefer using the array literal method, for simplicity, readability, and execution speed.

It is a common practice to declare arrays with the const keyword.

While creating an array, you can also spread the values inside the array out over multiple lines:

//Declaration of an Array
const country = [
                "India",
                "UK",
                "Japan"
                ];

Also, an array can hold all kinds of different data types — numbers, strings, functions, other arrays, objects, null, undefined, and boolean values as well. You can mix different types of data freely.

const Array = [ 10,                          // Number
                "name",                      // String 
                function x() {...},          // Functiom
                {"Saloni","Akriti"},         // Array
                {Book: "i like reading"},    // Object
                null,                        // Null
                undefined,                   // Undefined
                true                         // Boolean.
                ];

Indexing

You can access the values of an array by referring to an index number. The index number can be defined as the location of an item in the array.

Indexing of arrays starts from 0, which is called zero-based indexing. Let's look into it with an example.

const Array = ["My","name","is","Saloni"];
console.table(Array);

You can also access the values of the array by referring to the negative index number.

To get the value you refer to the members of an array using the index number in a square bracket []. This is known as bracket notation.

const Array = ["My","name","is","Saloni"];
console.log(Array[3]); //This will log "Saloni"

console.log(Array[-1]); //This will also log "Saloni"

Using the bracket notation, you can also create an empty array and then provide the elements to it:

const name = [];
name[0] = "Saloni";
name[1] = "Akriti";
name; // This will return ["Saloni", "Akriti"]

One interesting thing here is — you can change an element of the array, and add an element if needed, even with the array created with the keyword const.

name[0] = "Saloniverse";
name; // This will return ["Saloniverse", "Akriti"]

name[2] = "Hitesh"
name; // This will return ["Saloniverse", "Akriti", "Hitesh"]

But you can’t redeclare or reassign the value assigned to the variable name to a different value.

const numbers = [1, 2, 3];
numbers = [3, 2, 1];
//TypeError: Assignment to constant variable

Array Property and Method

Believe it!!! the strength of JavaScript arrays lies within the built-in array properties and methods.

The length Property

It returns the length or number of elements in an array. It is always one more than the highest array index.

const Feelings = ["Happy","Cheerful","Gleeful","Delighted","Lonely"];
Feelings.length; // Returns "5"

Array Methods

Array methods are functions built into JavaScript that you can apply to the arrays. Each method has a unique function that performs a change or calculation to your array and saves us from writing common functions from scratch.

Before diving into that, let's understand what's mutations. Arrays methods will fall into either category of destructive methods or nondestructive methods.

  • Destructive methods — will change or mutate the original array.

  • Nondestructive methods — will create a copy of the original array. It'll not change or mutate the original array.

    Generally, Nondestructive array methods are used, as we don’t want the information inside of the original arrays to change.

Accessing Element

concat()

  • This method is used to concatenate or merge two or more arrays.

  • It does not change the existing arrays, but returns a new array, containing the values of the joined array.

  • It can take any number of array arguments.

  • It can also take strings as arguments.

const arr1 = [1,2,3];
const arr2 = [4,5];
const arr3 = arr1.concat(arr2);
console.log(arr4); // Returns [1,2,3,4,5]

const arr4 = [6,7];
const arr5 = arr1.concat(arr2,arr4);
console.log(arr5); // Returns [1,2,3,4,5,6,7]


const arr6 = arr1.concat("Saloni");
console.log(arr6); // Returns [1,2,3,"Saloni"]

join()

  • The .join() method returns all the elements of an array into a new string.

  • The argument passed is known as the "separator".

  • If the separator argument is omitted, a comma (,) is used by default.

  • This is a non-destructive array method.

const country = [ 'India', 'UK', 'Japan' ];
const together = country.join(' and ');
console.log(together); // Returns "India and UK and Japan"

const together1 = country.join(); console.log(together1); // Returns "India,UK,Japan"

slice()

  • This method returns the selected elements in an array, as a new array object.

  • It returns a copy of an array, selecting from the given starting index to the given ending index.

  • The element at the given ending index is not included in the copy of the array.

  • Syntax: Array.slice(start, end)

start — an integer that specifies where to start the selection. Use negative numbers to select from the end of an array.

end — an integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

const life = ['eat', 'sleep', 'code', 'repeat'];
const slice1 = life.slice(1,3);
console.log(slice1); // This will log ['sleep', 'code']
console.log(life); // This will log ['eat', 'sleep', 'code', 'repeat'] -> The original array will remain intact.

  • The default option (with no arguments passed) is used to copy the entire array.
const slice2 = life.slice();
console.log(slice2); // This will log the copy of entire array ['eat', 'sleep', 'code', 'repeat']
  • We can also input just one argument to copy from that position to the end of the array or we can input both, for a more specific copy of an array.
const slice3 = life.slice(2);
console.log(slice3); // This will log ['code', 'repeat']
  • We can also use negative numbers to select elements starting from the end of the array.
const slice4 = life.slice(-4,-2);
console.log(slice4); // This will log  ['eat', 'sleep']

indexOf()

  • This method searches the array for the specified item and returns its position.

  • The search will start at the specified position, or at the beginning if no start position is specified, and end search at the end of the array.

  • If the item is not found, it simply returns -1.

  • It's a non-destructive array method.

const life = ['eat', 'sleep', 'code', 'repeat'];
const indexFound = life.indexOf('code');
console.log(indexFound); // This will log "2"

const indexNotFound = life.indexOf('enjoy');
console.log(indexNotFound); // This wil log "-1"
  • It returns the position of the first occurrence of a value in a string.
const complexlife = ['eat', 'sleep', 'code', 'eat', 'code'];
const indexFound = complexlife.lastIndexOf('code');
console.log(indexFound); // This wil log "2"

lastIndexOf()

  • This method returns the index (position) of the last occurrence of a specified value in a string.

  • It searches the string from the end to the beginning but, returns the index from the beginning (position 0).

  • It also returns -1, if the value is not found.

const complexlife = ['eat', 'sleep', 'code', 'eat', 'code'];
const indexFound = complexlife.lastIndexOf('code');
console.log(indexFound); // This wil log "4"

fill()

  • It fills specified elements in an array with a value.

  • This is a destructive array method.

  • Syntax: array.fill(value, start, end)

  • value - it is the value to fill in.

  • start - the start index, which is by default 0.

  • end - the end index, which is by default array.length.

  • If the start and end position is not specified, all the elements of the array will be filled.

  • It's a destructive array method.

const num1 = [1,2,3,4,5];
num1.fill('Saloni',2,4);
console.log(num1); // This will log [1, 2, 'Saloni', 'Saloni', 5]

const num2 = [1,2,3,4,5];
num2.fill('Saloni');
console.log(num2); // This will log ['Saloni', 'Saloni', 'Saloni', 'Saloni', 'Saloni']

Iterating I

forEach( )

  • It iterates over an array and executes the provided callback function for each element in an array.

  • It is not executed for empty elements.

  • It's a non-destructive array method.

const numbers = [1, 2, 3, 4];
numbers.forEach(myFunction);
console.log(numbers); // This will log [2,4,6,8]
function myFunction(item, index, arr){
    arr[index] = item * 2;}

const fWords = ["fact", "feel", "fear", "fail"];
fWords.forEach(word => console.log(word)); // This will log fact, feel, fear, fail and Return Undefined

every()

  • It executes a function for each array element.

  • It returns true if the function returns true for all elements.

  • It returns false if the function returns false for one element.

  • If the method finds an array element where the function returns a false value, every() returns false (and does not check the remaining values).

  • If no false occurs, every() returns true.

const fWords = ["fact", "feel", "feeling", "fear", "fail"];
fWords.every(word => word.charAt(0) === "f");  // Return "true"

some()

  • It executes the callback function once for each array element.

  • This is similar to the .every() method except it just checks for one success, instead of all.

  • If the method finds an array element where the function returns a true value, every() returns true (and does not check the remaining values).

  • It returns false, if the function returns false for all of the array elements.

const fWords = ["fact", "feel", "feeling", "fear", "fail"];
fWords.some(word => word.length > 6); // Return "true"

filter()

  • It returns a new array that’s filled with all the elements in an array that passes the provided test.

  • This is similar to .every() but returns a new array instead of a Boolean value.

  • It's a non-destructive array method.

const fWords = ["fact", "feel", "feeling", "fear", "fail"]; fWords.filter(word => word.length > 6); // Returns ['feeling']

includes()

  • The .includes() method returns true if the provided argument is included inside of an array.

  • It is similar to .every() but only checks for one element.

  • It is case-sensitive.

  • Syntax: array.includes(searchvalue, start);

  • search value - It is the array in which the search will take place.

  • start - This is optional, it determines the position from where the search will be processed. If it's not mentioned, the search will begin from the start of the array which is index number 0.

const num = [1,2,3,4,5,6,7,8];
console.log(num.includes(7); // This will log "true"

console.log(num.includes(7,6); // This will log "true"

Iterating II

map()

  • It iterates over an array and creates a new array with the results of calling a function for every array element.

  • It calls the provided function once for each element in an array, in order.

  • The returned array will always be the same length as the original array.

  • It's a non-destructive array method.

const numbers = [1,2,3,4];
const mapNumbers = numbers.map(item => item * 2);
console.log(mapNumbers); // This will log [2, 4, 6, 8]`

reduce()

  • It executes the provided callback function for each element in an array. The callback function is known as the "reducer".

  • This method will go from left to right and reduce all the elements in an array into a single value. This single value is known as the "accumulator".

  • .reduce() can also take an initial value as its second argument, which will then become the “starting point” for the accumulation. It’s generally good practice to include this second argument.

const numbers = [75, 50, 15];
sub = numbers.reduce(myFunc);
console.log(sub); // This will log "10"

function myFunc(total, num){
    return total - num;} 

const numbers = [1, 2, 3, 4];
sum = numbers.reduce(getSum, 100); // Here initial value is 100
console.log(sum); // This will log "110"

function getSum(total, num){
    return total + num;}

reduceRight()

  • It executes the provided callback function for each element in an array. The callback function is known as the “reducer”.

  • This method will go from right to left and reduce all the elements in an array into a single value. This single value is known as the “accumulator”.

  • .reduceRight() can also take an initial value as its second argument, which will then become the “starting point” for the accumulation. It’s generally good practice to include this argument.

const numbers = [15, 50, 75];
sub = numbers.reduceRight(myFunc);
console.log(sub); // This will log "10"

function myFunc(total, num) {
    return total - num;}

Mutating

pop()

  • This method removes the last element from an array and then returns the removed element.

  • It is similar to .shift() except it removes the last element instead of the first, which is discussed below in detail.

  • It changes both the array and its length.

  • It's a destructive array method.

const life = ['eat', 'sleep', 'code', 'repeat'];
life.pop(); // This will return 'repeat'
life; // This will return ['eat', 'sleep', 'code']

push()

  • It adds one or more elements to the "end" of an array and returns the "new length of the array".

  • It is similar to .unshift() except it adds to the end of the array instead of the front, which is discussed below in detail.

  • This method also changes both the array and its length.

  • It's a destructive method.

const life = ['eat', 'sleep', 'code', 'repeat'];
life.push('play'); // This will return '5'
life; // This will return ['eat', 'sleep', 'code', 'repeat', 'play']

reverse()

  • This method reverses the order of the elements in an array.

  • The first element becomes and last and the last element becomes the first.

  • It overwrites the original array. It's a destructive array method.

const intro = ["My","name","is","Saloni"];
intro.reverse(); // This will return ['Saloni', 'is', 'name', 'My']

sort()

  • This method sorts the elements of an array.

  • It sorts the elements as strings in alphabetical and ascending order.

  • It overwrites the original array. It's a destructive array method.

const numbers = [3,7,5,2,1,9,0];
numbers.sort(); // This will return [0, 1, 2, 3, 5, 7, 9]

splice()

  • This method changes the contents of an array by either removing elements or adding new elements, and returns the removed item(s).

  • .splice() can take 3 or more arguments.

  • The first argument will be the index where to add or remove items.

  • The second (optional) argument will be how many items to remove, even 0.

  • The rest of the arguments will be all the new elements to add into the array.

  • You can also use negative numbers to select elements starting from the end of the array.

  • It's a destructive method.

const country = ["India", "UK", "Japan"];
country.splice(0); // Returns ['India', 'UK', 'Japan']
country; // Returns []

// Remove item from array
const country2 = ["India", "UK", "Japan"];
country2.splice(1, 2); // Returns ['UK', 'Japan']
country2; // // Returns ['India']

// Add items to array
const country1 = ["India", "UK", "Japan"];
country1.splice(2, 0, "France", "Germany"); // Returns []
console.log(country1); // Returns ['India', 'UK', 'France', 'Germany', 'Japan']

const country3 = ["India", "UK", "Japan"];
country3.splice(-2); // Returns ['UK', 'Japan']
country3; // Returns ['India']

shift()

  • It removes the first element from an array and then returns the removed element.

  • It is similar to .pop() except it removes the first element instead of the last.

  • This method changes both the array and its length.

  • It's a destructive array method.

const life = ['eat', 'sleep', 'code', 'repeat'];
life.shift(); // This will return "eat"
life; // This will return ['sleep', 'code', 'repeat']

unshift()

  • It adds one or more elements to the "front" of an array and returns the "new length of the array".

  • It is similar to .push() except it adds to the front of the array instead of the end.

  • This method also changes both the array and its length.

  • It's a destructive method.

const life = ['eat', 'sleep', 'code', 'repeat'];
life.unshift('play'); // This will return '5'
life; // This will return ['play', 'eat', 'sleep', 'code', 'repeat']

General

toString()

  • This method returns a string with an array’s elements separated by commas.

  • It is used when an object needs to be displayed or used as a text/string.

  • It's a non-destructive method.

const life = ['eat', 'sleep', 'code', 'repeat'];
life.toString(); // This will return 'eat,sleep,code,repeat'

toLocaleString()

  • This method also returns a string with an array’s elements separated by commas.

  • It is generally used while representing a Date object as a string, using locale settings.

  • The default language will depend on the locale setup on your computer.

const myArray = [100, 'Saloni', new Date()];
let myString = array.toLocaleString();
console.log(myString); // This will log "100,Saloni,01/01/2022, 12:00:00 AM"

isArray()

  • It determines whether the passed value is an Array.

  • It returns true if an object is an array, otherwise false.

  • Syntax: Array.isArray(obj);

// Below calls will return true
    Array.isArray([]);
    Array.isArray([1,2,3]);
    Array.isArray(new Array());
    Array.isArray(new Array("a", "b", "c", "d"));
    Array.isArray(new Array(369));
    Array.isArray(Array.prototype);

// Below calls will return false
    Array.isArray();
    Array.isArray({});
    Array.isArray(null);
    Array.isArray(undefined);
    Array.isArray(10);
    Array.isArray("Array");
    Array.isArray(true);
    Array.isArray(false);
    Array.isArray(new Uint8Array(32));

Thanks for scrolling this far.

Hope you find this post helpful.

Learn more about JavaScript Array from MDN Docs