Stack and Queue in JavaScript and wrapper implementation in TypeScript

Reading Time: 4 minutes

Stack and Queue are among the most popular collections used in mordern programming languages like C# and Java. Here in this article we will discuss about how this is implemented in JavaScript.

Stack and Queue


var stack = [];


As we all know Stack follows FILO (First In Last Last Out) mechanism. So in the above example we are creating an empty array and performing two push action. First we have pushed “A” then “B” so when you pop result is going to be “B”



var queue = [];


here if you notice we are still using method push() and then new method shift() and result expected is A when you pull the last inserted since it follows FIFO (First In First Out).

From the above two code snippets we can make out that array is not type safe you can have any types in it like

var stack = [];
stack.push({ name: 'shawn', age: 20 });

So to avoid it we can have wrapper function or class in JavaScript since guys who are new to JavaScript coming from C# and Java might find it difficult to so I am going to share TypeScript implementation which is a superset of JavaScript

class Stack<T>{
    _stack: T[];

    constructor(stack?: T[]) {
      this._stack = stack || [];

    push(item: T) {

    pop(): T {
      return this._stack.pop();
    clear() {
      this._stack = [];

    get count(): number {
      return this._stack.length;

class Queue<T>{
    _queue: T[];

    constructor(queue?: T[]) {
      this._queue = queue || [];

   enqueue(item: T) {

   dequeue(): T {
     return this._queue.shift();

   clear() {
     this._queue = [];

   get count(): number {
     return this._queue.length;

let stack = new Stack<number>();
stack.push("A");//It will throw error when you compile 

Code can be found at stack and queue

If you notice the last 3 lines of the snippet code above Stack instance is of type number we are trying to push(“A”) which is of string now when you complie the above TypeScript implementation it will show as Error like Argument of type ‘”A”‘ is not assignable to parameter of type ‘number’. so better use TypeScript for type safe coding practice. If you are using IDE’s like Visual Studio Code it will highlight that there is an error.

When you compile this TypeScript (TS) it will generate equivalent JavaScript code. With the addition of tsconfig.json configuration file to the solution we can target it to ES6 or ES5 or whatever version of ES/JavaScript.

Note: You can play around with TypeScript code at  Microsoft's TypeScript Playground

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.