Array Data Structure – What you should know?

Already in previous post we have seen about the Data Strucutres in JavaScript. Now we will jump into the creation and implementation of arrays.

As you already know, array represents collection of similar data items. It is an object that stores multiple data items.

 Array Declaration:

By array literal

Simplest way to create an array is by using array literal [ ].

Syntax:

               let arrayname = [value1, value2, value3,….]

By new keyword
Syntax:

               let arrayname = new Array();

//creates an array with 6 elements using array literal
var arr1 = [2,3,1,4,5,7];
//create array using new keyword
var arr2 = new Array(1,3,5,7,9,0);
//create an array with undefined elements
var arr3 = new Array();
//provide elements in arr3
arr3[0] = "Apple";
arr3[1] = "Orange";
arr3[2] = "Banana";
//create an array with 2 elements
var arr4 = new Array("Tom","Paul");
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
Output:
Accessing arrays:

Elements of an array are accessed using indexes.

var arr1 = [2,3,1,4,5,7];
//first element
console.log(arr1[0]);
//fourth element
console.log(arr1[3]);
Output:

2

4

Adding elements to an array:

We use push() and unshift( ) methods to add elements to an array.

push() method adds elements to the end of an array.

unshift() method adds elements to the start of an array.

let fruits = ["apple","orange"];
//using push() method
fruits.push("banana");
//using unshift() method
fruits.unshift("grapes");
console.log(fruits);
Output:

Now what will happen to the above array fruits if we try to add an element at index 5 rather than index 4?

Let’s see,

let fruits = ["grapes","apple","orange","banana"];
//add element at index 5
fruits[5]="strawberry";
console.log(fruits);
Output:

So index 4 will be undefined.

Remove an element from an array:

Here also we can remove from start or end using pop() and shift() methods.

pop() removes the last element

shift() removes the first element

let fruits = ["grapes","apple","orange","banana"];
//pop() method
frutis.pop();
console.log(fruits);
//shift() method
console.log(fruits);
Output:
How to find the length of an array?

It is done by length property. Returns the number of elements in an array.

let fruits = ["grapes","apple","orange","banana"];
console.log(fruits.length);
Output:

4

Methods in an array data structure:

In JavaScript arrays there are various methods available.

MethodsDescription
concat()joins two or more arrays and returns a result
indexOf()searches an element of an array and returns its position
find()returns the first value of an array element that passes a test
findIndex()returns the first index of an array element that passes a test
forEach()calls a function for each element
includes()checks if an array contains a specified element
push()adds a new element to the end of an array and returns the new length of an array
unshift()adds a new element to the beginning of an array and returns the new length of an array
pop()removes the last element of an array and returns the removed element
shift()removes the first element of an array and returns the removed element
sort()sorts the elements alphabetically in strings and in ascending order
slice()selects the part of an array and returns the new array
splice()removes or replaces existing elements and/or adds new elements
let fruits = ["grapes","apple","orange","banana"];
//sort in alphabetical order
fruits.sort();
console.log(fruits);
//find the index position
const pos = fruits.indexOf("apple");
console.log(pos);
//slicing array
const frutis1 = fruits.slice(2)
console.log(fruits1);
//concat two arrays
const frutis2 = frutis.concat(fruits1);
Output:

Difference between var, let and const in Javascript

The var, let and const are the keywords basically used in Javascript to declare variables. Among them var is the oldest way of declaring a variable. Other two let and const are introduced in ES2015 (ES6) update. Nowadays let and const are used more frequently in modern javascript compared to var.

In this article, we will try to understand the difference between them in respect to their scope.

Before getting into the difference first we need to know what is function scope and block scope.

Function Scope – Created by declaring a function

Block Scope – Created by if statement, for loops, while loops etc.

var in Javascript:

Var declarations are globally or functionally scoped. The var is globally scoped when it is declared outside a function and it is available for the whole program. Var is functionally scoped when it is declared inside a function.

Example of var with global scope:

Output:

2

2

The scope of variable a is global and it can be accessed anywhere in the program.

Example of var with function scope:

Output:

2

Reference Error: a is not defined

The scope of variable is within the function so if we try to access outside the function it shows error.

Limitation with var:

Var variable can be redeclared and updated. If we accidentally declared a new variable with the same name, it will override the existing value of that variable.

Output:

7

Last assigned value 7 is updated to the variable a.

If we use the var variable before declaration it is initialized with undefined value.

Output:

Undefined.

Let in javascript:

It is an improved version of var keyword. Let does not allow variable redeclaration.

Output:

Syntax error: Identifier ‘a’ has already been declared.

Scope of let:

Let is block scoped.

Output:

20

10

Now try to access b outside the function.

Output:

Reference Error : b is not defined.

If we use a variable before declaration it is not initialized with undefined just returns an error.

Output:

Reference Error: Cannot access ‘a’ before initialization

const in javascript:

Const variables maintain constant values. They share some similarities with let.

Like let declarations, const are block scoped. The difference is that unlike let, const cannot be updated or re-declared.

Output:

Type Error: Assignment to constant variable

User cannot change the properties of const object but they can change the value of properties of const object.

Output:

Type Error : Assignment to const variable.

Points to remember

varletconst
Function scopedBlock scopedBlock scoped
Allow duplicate identifiersDoes not allow duplicate identifiersDoes not allow duplicate identifiers
Value can be updatedValue can be updatedValue cannot be updated
Hoisted and initialized with undefinedHoisted but error if we try to access before declarationHoisted but error if we try to access before declaration