All about Arrays in JavaScript

All about Arrays in JavaScript

What is JavaScript?

JavaScript is one of the most popular and widely used programming languages in the world right now. It is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. With this programming language, you can make your website more lively, robust, and interactive.

These days we can build web and mobile apps, as well as Real-time networking apps like chats and video streaming services, command line tools, or even games.

In this article, we will dive into the concept of arrays in javascript. We will go through each and every method in arrays with examples. Let us start with the array definition.

What Are Arrays in JavaScript?

Arrays in JavaScript are the data type used to store a list of values. JavaScript array objects can be stored in variables and dealt with in the same way you deal with any other data type. The difference is that we can access each value inside the list individually, and perform various activities, such as looping over it.

In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics:

  • JavaScript arrays are resizable and can contain a mix of different data types. (When those characteristics are undesirable, use typed arrays instead.)

  • JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.

  • JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.

  • JavaScript array-copy operations create shallow copies. (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies).

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

syntax:

const array_name = [item1, item2, item3 ...];

Examples:


// Example 1
const array1 = ["Suresh", "Ramesh", "Ganesh"];
console.log(array1);

// output :
["Suresh","Ramesh","Ganesh"]

// Example 2 ( You can also create an array first and then add values to it)
const array2 = [];
array2[0] = "Nissan";
array2[1] = "Audi";
array2[2] = "Ferrari";

// output :
console.log(array2);
["Nissan","Audi","Ferrari"]

There is another way of creating an array by using the JavaScript Keyword new.

Syntax:

const array_name = new Array(item1, item2, item3 ...);

Examples:


// Example 1
const array1 = new Array("Suresh", "Ramesh", "Ganesh");
console.log(array1);

// output :
["Suresh","Ramesh","Ganesh"]

// Example 2 ( You can also create an array first and then add values to it)
const array2 = new Array();
array2[0] = "Nissan";
array2[1] = "Audi";
array2[2] = "Ferrari";
console.log(array2);

// output :
["Nissan","Audi","Ferrari"]

The two examples above do exactly the same.

There is no need to use the new Array(). For simplicity, readability, and execution speed, use the array literal method.

The length Property

The length property of an array returns the length of an array (the number of array elements).

syntax:

array_name.length;

Example

const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(cars.length);

// output:
4

Accessing Array Elements

We access an array element by referring to the index number.

  • JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.

Syntax:

array_name[index_number];

Example:


// Example 1
const array = ["Suresh", "Ramesh", "Ganesh","Naresh"];

// To print the first element in the array.
console.log(array[0]);

// output :
"Suresh"

// To print the second element in the array.
console.log(array[1]);

// output :
"Ramesh"

// To print the last element in the array. Here (array.length method gives the length of the array)
console.log(array[array.length-1]);

// output :
"Naresh"

Changing an Array Element

In Order to change the value of array elements. First, we need to access them with the targeted index values and assign the new value to them.

Syntax:

array_name[index_value] = new_value;

Example:

// Given Array
const array = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(array[2]);

// output
 "Ferrari"

// This will change the third element value in the array from "Ferrari" to "Nexus"
array[2] = "Nexus";
console.log(array[2]);

// output
"Nexus"

Arrays are Objects

Arrays are a special type of object. The typeof operator in JavaScript returns "object" for arrays.

const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(typeof((cars));

// output:
object

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access their "elements". In this example, cars[0] returns "Nissan":

Example:

// Given Array
const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(cars[0]);

// output:
"Nissan"

Objects use names to access its "members". In this example, person.firstName returns John:

Example:

// Given Array
const person = {firstName:"John", lastName:"Doe", age:46};
console.log(person.firstName);

// output:
"John"

Array Elements Can Be Objects

  • JavaScript variables can be objects. Arrays are special kinds of objects.
  • Because of this, you can have variables of different types in the same Array.
  • You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array.

Array Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Converting Arrays to Strings

toString() method

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Syntax:

array_name.toString();

Example:

const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(cars.toString());

// output
Nissan,Audi,Ferrari,Porsche

join() method

The join() method also joins all array elements into a string. It behaves just like toString(), but in addition, you can specify the separator.

Syntax:

array_name.join();

Example:

const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(cars.join("*"));

// output
Nissan*Audi*Ferrari*Porsche

Popping and Pushing

By using pushing and popping methods, it is easy to remove elements and add new elements to the array.

Popping items out of an array, or pushing items into an array.

pop() method

The pop() method removes the last element from an array.

syntax

array_name.pop();

Example:

const array = ["Nissan", "Audi", "Ferrari","Porsche"];
array.pop();
console.log(array);

// output
[ 'Nissan', 'Audi', 'Ferrari' ]

push() method

The push() method adds a new element to an array (at the end).

syntax

array_name.push("new_element");

Example:

const array = ["Nissan", "Audi", "Ferrari","Porsche"];
array.push("Tesla");
console.log(array);

// output
[ 'Nissan', 'Audi', 'Ferrari', 'Porsche', 'Tesla' ]

Shifting Elements

Shifting is equivalent to popping, but working on the first element instead of the last.

shift() method

The shift() method removes the first array element and "shifts" all other elements to a lower index.

syntax

array_name.shift();

Example:

const array = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(array.shift());

// output
Nissan

unshift() method

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.

syntax

array_name.unshift("new_element");

Example:

const array = ["Nissan", "Audi", "Ferrari","Porsche"];
array.unshift("Tesla");
console.log(array);

// output
[ 'Tesla', 'Nissan', 'Audi', 'Ferrari', 'Porsche' ]

concat() method

The concat() method creates a new array by merging existing arrays.

syntax

array1_name.concat(array2_name);

Example:

const array1 = ["Nissan", "Audi"];
const array2 = ["Ferrari","Porsche"];
const cars = array1.concat(array2);
console.log(cars);

// output
[ 'Nissan', 'Audi', 'Ferrari', 'Porsche' ]

Splicing and Slicing Arrays

  • The splice() method adds new items to an array.
  • The slice() method slices out a piece of an array.

splice() method

The splice() method can be used to add new items to an array.

syntax

array_name.splice(new_elements_position, no_of _elements_to_add,item1,item2,..);
  • The first parameter defines the position where new elements should be added (spliced in).

  • The second parameter defines how many elements should be removed.

  • The rest of the parameters ("item1", "item2") define the new elements to be added.

The splice() method returns an array with the deleted items:

Example:

const cars = ["Nissan", "Audi", "Ferrari","Porsche"];
console.log(cars.splice(2, 2, "Tesla", "Honda"));

// output
[ 'Ferrari', 'Porsche' ]

slice() method

The slice() method slices out a piece of an array into a new array.

syntax

array_name.slice(index_value);
  • The slice() method creates a new array.
  • The slice() method does not remove any elements from the source array.

Example:

const cars =  ["Nissan", "Audi", "Ferrari","Porsche","Tesla"];
const newCars = cars.slice(3);
console.log(newCars);

// output
[ 'Porsche', 'Tesla' ]

The slice() method can take two arguments like slice(start_index, end_index).

The method then selects elements from the start argument, and up to (but not including) the end argument.

syntax

array_name.slice(start_index_value, end_index_value);

Example:

const cars =  ["Nissan", "Audi", "Ferrari","Porsche","Tesla"];
const newCars = cars.slice(1,3);
console.log(newCars);

// output
[ 'Audi', 'Ferrari' ]

Sorting Methods in Arrays

sort() method

The sort() method sorts an array alphabetically and for numbers, it sorts in ascending order.

syntax

array_name.sort();

Example:

const cars =  ["Nissan", "Audi", "Ferrari","Porsche","Tesla"];
console.log(cars.sort());

// output
[ 'Audi', 'Ferrari', 'Nissan', 'Porsche', 'Tesla' ]

const cars =  [5,2,3,4,1];
console.log(cars.sort());
// output
[ 1, 2, 3, 4, 5 ]

reverse() method

The reverse() method reverses the elements in an array.

syntax

array_name.sort();

Example:

const cars =  ["Nissan", "Audi", "Ferrari","Porsche","Tesla"];
console.log(cars.reverse());

// output
[ 'Tesla', 'Porsche', 'Ferrari', 'Audi', 'Nissan' ]

const cars =  [5,2,3,4,1];
console.log(cars.reverse());
// output
[ 1, 4, 3, 2, 5 ]

Array Iteration methods

Array iteration methods operate on every array item.

map() method

map() is basically used to transform an array.

  • The map() method creates a new array by performing a function on each array element.
  • The map() method does not execute the function for array elements without values.
  • The map() method does not change the original array.

Example

const arr = [5,3,1,2,6];

function double(x){
    return x*2;
}

const output = arr.map(double);

console.log(output);

// output:
[ 10, 6, 2, 4, 12 ]

filter() method

filter() is used to filter the values in an array.

  • The filter() method creates a new array with array elements that passes a test.

Example

const arr = [5,3,1,2,6];

const isOdd = function(x){
    return x%2;
}

const output = arr.filter(isOdd);

console.log(output);

// output:
[ 5, 3, 1 ]

reduce() method

reduce() is basically used at a place where you have to take all the elements of an array and come up with a single value out of them.

  • The reduce() method runs a function on each array element to produce (reduce it to) a single value.
  • The reduce() method works from left-to-right in the array.

Example

const arr = [5,1,3,2,6];

function findSum(arr){
    let sum = 0;
    for(let i=0; i<arr.length; i++)
    {
        sum = sum+arr[i];
    }
    return sum;
}

console.log(findSum(arr));

// output:
17

indexOf() method

The indexOf() method searches an array for an element value and returns its position.

syntax

array.indexOf(element);

Example

const array = ["Nissan", "Audi", "Ferrari","Porsche"];

console.log(array.indexOf("Ferrari"));

// output:
2

Closing

I hope that you’ve found this blog and the examples on Arrays in javascript helpful! If you have any questions or feedback, feel free to leave a comment below 😊