How to implement Stack data structure in JavaScript?

We have already seen about Array Data Structure. Stack data structure is implemented using arrays. With push(), pop(), shift(), unshift() we create stack . For creation of stack we always prefer push() and pop(). Now let us implement stack data structure.

Methods to implement Stack Data Structure :

  • push() – adds an element at top of the stack
  • pop() – removes the top most element of the stack and if it is called on an empty stack returns ‘underflow’
  • peek() – similar to pop() returns top most element but does not delete it.
  • isEmpty() – return true if stack is empty.
  • printStack() – returns a string in which all elements of the stack are concatenated.
Program to implement Stack :
class Stack {

    constructor() {

        this.items = [];

    }

    // add element to the stack

    add(element) {

        return this.items.push(element);

    }

    // remove element from the stack

    remove() {

        if(this.items.length > 0) {

            return this.items.pop();

        }

    }

    // view the last element

    peek() {

        return this.items[this.items.length - 1];

    }

    // check if the stack is empty

    isEmpty(){

       return this.items.length == 0;

    }

    // the size of the stack

    size(){

        return this.items.length;

    }

    // empty the stack

    clear(){

        this.items = [];

    }

}

let stack = new Stack();

stack.add(10);

stack.add(20);

stack.add(30);

stack.add(40);

console.log(stack.items);

stack.remove();

console.log(stack.items);

console.log(stack.peek());

console.log(stack.isEmpty());

console.log(stack.size());

stack.clear();

console.log(stack.items);
Output:

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:

What is the difference between OOP and Functional programming

ParameterObject Oriented ProgrammingFunctional Programming
DefinitionA programming paradigm based on the concept of objects which contains data in the form of fields called attributes and code in the form of methodsA programming paradigm based on the concept of procedure calls
Paradigm
ApproachBottom-up ApproachTop-down Approach
Data ControlIn OOP data in each function is controlled on its ownIn POP every function has different data so no control over it.
EmphasisEmphasis on objectsEmphasis on functions
CommunicationObjects communicate with each other by message passingParameters communicate with each other by parameter passing
InheritanceInheritance is supported by three modes : private, protected and publicInheritance is not supported
Access ControlAccess control is done with access modifiersAccess modifiers is not supported
Data HidingData can be hidden is using EncapsulationNo data hiding. Data is accessible globally
Overloading or PolymorphismOverloading functions, constructors and operators are possibleOverloading is not possible
SecurityMore secured language because external functions can’t access another data.Due to global data, it is less secured language
Code reusabilityExisting code can be reusedNo code reusability
Problem SolvingUsed for solving big problemsNot used for solving big problems
ExampleC++, Java,C#, PHP, PythonCOBOL, C, FORTRAN, BASIC, PASCAL