Arrays in Javascript

Published on Aug 14, 2021
3 min read

Welcome back developers !

If you are someone who just started programming then this is a must read blog for you.

In this blog , we will be covering Arrays.

What is an Array ?

Array is a datastructure which is used to store multiple values in a single variable. (i.e : we can store more than one value at a time).


Consider a case , where you are supposed get all students name of a department. In this case you can't create a separate variable for storing each student name.

But what if you can create a variable of dept_name and have all the students name belonging to that department. Sounds cool right , this is the concept of arrays.

Syntax

Example:

Unlike C , C++ languages Javascript arrays can store values of different datatypes in a single array.


Accessing the array elements

The values of a array can be accessed using index. The index of an array starts from 0 to length of the array - 1.

ie: If you wanna access the first element of the array , then you need to mention the index value as 0.

Syntax

If you use a invalid index it would return undefined.

What if you do know the size of the array ?

Array has a property which would return the length of the array. ie.array_name.length


Methods

1. push

This method is used to add elements into the array . It adds the elements at the end of the array.



2. pop

This method is used to remove elements from the end of the array.



3. unshift

This method is used to add elements in the beginning of the array.



4. shift

This method is used to remove elements from the beginning of the array.



5. indexOf

This method returns the index(ie.position of the element) of element in the array. When there are duplicates it would return the first occuring index.



6. splice

This method takes two arguments one is pos(ie.position of the element to be removed) and other is noOfElements from that position to be removed;

array_name.splice(pos , n);


These are the basic array methods that are frequently used in programming.

If you wanna learn more about array methods , check this out :

© 2021 Devananth Nkl's Blog