Understanding javascript arrays for beginners
By: Prabhat Giri
Tags: Javascript Arrays, Web Development, Javascript Development, JavaScript, Arrays

Arrays are the most common data structure used in computer programming. In this article we are going to talk about using arrays in javascript, don’t worry if you are not familiar with arrays in any programming language, we are going to talk about javascript arrays from scratch.

Definition

Javascript arrays can be considered as containers to store items that can fetched using a single variable.The best thing about arrays in javascript unlike other programming languages is that you can store items of different datatypes in a single array.Lets check an example that justifies my above claim.

var arr = ["Hello", 1 , 2 , "World"];

The array arr has two String elements i.e "Hello" and "World" and also two Number elements i.e 1 and 2 which is completely fine in javascript unlinke other languages.

Creating array

We can create an array in two ways. Let’s check them one by one

Method One

Arrays in javascript can be easily created using the array literal.

var array_name = [element1 , element2 , element3,....]; var arr = ["Hello", 1 , 2 , "World"];

Method two

Another way to create array in javascript is using the Array constructor and new keyword.

var array_name = new Array(array_length);

var array_name = new Array(element1,element2,element3,...);

var arr = new Array(5);

var arr = new Array("Hello", 1 , 2 , "World");

So if you closely observe the above two snippets you would understand that passing a single parameter into the Array constructor will create an empty array of the parameter length but if you pass multiple parameters , it will create an array with the parameters as elements of the array.

Accessing elements of array

The elements of an array can be accessed by indices, which are integers used to compute offset.

Iterating elements of array

The iteration of array can be achieved using several pre-defined methods .These methods can be broadly divided

two parts:

1. Non-array generating methods

2. Array generating methods

Lets take a look at these categories and the methods under them

Non-array generating methods

The non-array generating methods iterate the array without creating any new array. Let’s talk about the methods that come under this category

This method takes a function as parameter and applies it to each element of the array while iterating it’s elements.

5,10,15,20,25,30,35

This method takes a boolean function as parameter and returns true if the parameter function returns true for every element of the array

var numbers= [3,6,9,18,15,10];

var multipleOfThree= numbers.every(function(value){

return value%3==0;

})

if(multipleOfThree){

console.log("All elements are multiple of 3");

}

else{

console.log("Not all elements are multiple of 3");

}

Not all elements are multiple of 3

Value of multipleOfThree will be False because all elements in the array are multiples of 3 except the last element i.e 10

This method takes a boolean function as parameter and returns true if the parameter function returns true for any element of the array

var numbers= [3,9,18,15];

var multipleOfTwo= numbers.some(function(value){

return value%2==0;

})

if(multipleOfTwo){

console.log("Few elements are multiple of 2");

}

else{

console.log("All elements are not multiple of 2");

}

Few elements are multiple of 2

Value of multipleOfTwo will be True because we have alteast one element i.e 18 which is multiple of 2

This method applies a function to an accumulator and the successive elements of an array until it reaches the last element. Thus, it yields a single value

The below source code uses reduce() to calculate the sum of all elements of an array

Sum of all elements is, 55

reduceRight()

This method works similar to reduce() , the only difference is that it operates from the right hand side.Let's see an example of how it can be used to concat string elements of an array to form a complete sentence.

Javascript is love

Array generating methods

These methods return new array after they successfully iterate through all elements of the array.Let’s take a look at the methods that are of this category.

This method works similar to forEach() ,the difference is that it return a new array. Let's see an example where we will use map() to multiple all elements of an array with 5 and return the result as a new array

(5) [5, 10, 15, 20, 25]

Please note that result is a new array.

This method works similar to every() but instead of returning true if all the elements satisfy a boolean function, it returns a new array with elements that satisfy the boolean function.

var numbers = [1,2,3,4,5];

var even = numbers.filter(function(value){

return (value%2==0)?true:false;

});

console.log("The array with even elements:");

console.log(even);

The array with even elements: (2) [2, 4]

Copying javascript arrays

When you assign an array to another it is copied by reference and not by value.What i mean by it that if you modify the later array then the original array will also be changed automatically, which we will never want in general circumstances.let’s understand this with an example.

(3) ["Apple", "Mango", "Pineapple"] (3) ["Apple", "Mango", "Pineapple"]

As you can see both the arrays fruits and anotherFruits gets modified when we add another element to the anotherFruits arrays. The result will also be same if we modify the fruits array. This way of assigning arrays in javascript is called Shallow copying.

An alternative to this is called Deep copying. It makes sure that just the elements of each array gets copied and not the complete array.let’s try to achieve this with the help of a function.

function arraycopy(array1,array2){

for(var i =0;i< array2.length;i++){

array1[i]=array2[i];

}

}

var fruits=["Apple","Mango"];

var anotherFruits=[];

arraycopy(anotherFruits,fruits);

anotherFruits.push("Pineapple");

console.log(anotherFruits);

console.log(fruits);

(3) ["Apple", "Mango", "Pineapple"] (2) ["Apple", "Mango"]

So, the moment we assign each element of an array to another, we are no more under threat of auto modification of original array contents.

Other important array methods in javascript

This method joins two or more arrays. Please note that it doesn’t change the existing array rather returns a new array containing values of the joined array.

(4) ["Prabhat", "Subhajit", "Ankita", "Sarita"]

It creates a string from the array with the elements seperated by the specified seperator.The default is comma(,)

Prabhat is friend with Subhajit

It removes and returns the first element of an array.

Prabhat

It removes and returns the last element of an array.

Subhajit

It adds new elements at the end of an array and returns the length of the updated array.Please note that it modifies the original array.

(4) ["Prabhat", "Subhajit", "Ankita", "Sarita"]

This method reverses the order of elements of an array.

(4) ["Sarita", "Ankita", "Subhajit", "Prabhat"]

This method selects elements from a specified point to an end point without including the end point element.Please note that it doesn’t modify the original array.

(2) ["Subhajit", "Ankita"] (2) ["Subhajit", "Ankita"]

This method adds or removes elements of an array at specified positions and returns the added/removed elements.

// Add elements

// We are adding two elements at position 1 of the array persons

var persons=["Prabhat","Subhajit"];

persons.splice(1,2,"Ankita","Sarita");

console.log(persons);

// Remove elements

// We are removing two elements from positon 2 of the persons array

var newpersons=["Prabhat","Subhajit","Ankita","Sarita"];

newpersons.splice(2,2);

console.log(newpersons);

(3) ["Prabhat", "Ankita", "Sarita"] (2) ["Prabhat", "Subhajit"]

This method sorts the element of an array.The order can be numeric or alphabetic and ascending or descending.By default the sorting is alphabetical and in ascending order.There is a problem when you sort numbers as strings.For example when you sort 21 and 100 , logically 21 should come first but when you sort it as strings “1” is less than “2” so 100 will come first.This problem can be solved by using a comparison function with sort() .Please note that this method changes the original array.

(6) [7, 10, 19, 25, 42, 234]

It works similar to join() , the only difference is it doesn't need any argument and returns comma (,) separated string form of all elements of the array.

Prabhat,Subhajit,Ankita,Sarita

This method return the position(index) of an element in an array.It return -1 if the element is not found.

var persons=["Prabhat","Subhajit","Ankita"];

var position= persons.indexOf("Subhajit");

//Let's find position of an element that doesn't exist

var unKnownPosition= persons.indexOf("Sarita");

console.log(position);

console.log(unKnownPosition);

1

-1

Huh ! i know it was a long one but i am sure by now you have decent knowledge of Arrays in javascript, I can’t wait to have some good discussions in the comments.Feel free to ask your queries or let me know how helpful you found this article.

Happy coding !!!!!