Understanding javascript arrays for beginners - Meteorio

Understanding javascript arrays for beginners

| 5 years ago

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.

Syntax

var array_name = [element1 , element2 , element3,....];

Example

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

Method two

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

Syntax

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

Example

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.

Advertisement
 

Accessing elements of array

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

Example

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

forEach()

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

Example

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

every()

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

Example

Output
 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

some()

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

Example

Output
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

reduce()

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

Example

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

Output
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.

Example

Output
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.

map()

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

Example

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

Please note that result is a new array.

filter()

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.

Example

Output
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.

Example

Output
(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.

Example

Output
(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.

Advertisement

Other important array methods in javascript

concat()

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.

Example

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

join()

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

Example

Output
 Prabhat is friend with Subhajit

shift()

It removes and returns the first element of an array.

Example

Output
 Prabhat

pop()

It removes and returns the last element of an array.

Example

Output
 Subhajit

push()

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.

Example

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

reverse()

This method reverses the order of elements of an array.

Example

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

slice()

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.

Syntax

Example

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

splice()

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

Syntax

Example

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

sort()

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.

Example

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

toString()

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.

Example

Output
      Prabhat,Subhajit,Ankita,Sarita

indexOf()

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

Example

Output
     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 !!!!!

About Author

User profile picture

Prabhat Giri

Software engineer (@Prabhat Giri)

Hi thanks for reading my blog. I am a software professional who is also passionate about business and travelling.

Popular topics

Career Javascript Web Development Job Preparation Angular Geekncoder

Adverts *