JavaScript Top Interview questions

JavaScript Interview Questions
JavaScript Interview Questions

What is the difference between __proto__  vs Prototype?

Whenever we create a function in JavaScript. JavaScript engine itself adds a property to that function and that is called prototype. This Prototype has a constructor property by default that points back to the main function. We can access prototypes by writing syntax like functionName. prototype.

function Java(v) {
    this.version = v;
    this.updateVersion = function(v) {
        this.version = v;

So by Using Java.prototype – we can prototype. And when we do Java.prototype.constructor – it returns the same java function.

Now when we create an object of a function, JavaScript adds a property proto to that newly created object which is called dunder proto. Dunder proto or proto points to the prototype object of that constructor function.

Java.prototype === obj.__proto__ // result > true

There is only one object that is used for prototype chaining. This object obviously has a name and a value: proto is its name, and prototype is its value. That’s all.
Every instance created using new Java() has a proto property that points to the Java.prototype. This is the chain that is used to traverse to find a property of a particular object.
Read here more..

How can we create Abstract Class In Vanilla JavaScript?

Abstract class is a class that is created by using the abstract keyword in Es6. We cannot create an object of such classes directly by using the new keyword. It may or may not contain an abstract method.
Abstract methods are those methods that don’t have a body and are initialized by using the Abstract keyword. Let’s see how we can achieve this in Vanilla JavaScript.

  var Shape = function(){
    this.shapeName = 'Shape';
    throw new Error("can't create object of abstract class");
  Shape.prototype.AbstractMethodSize = function() {
    throw new Error('must implement in sub class');
  Shape.prototype.draw = function() {
      return this.shapeName;

  var s = new Shape();
  //output > Uncaught Error: can't create object of abstract class

  var Square = function() {
    this.shapeName = 'square';
  // We can create an object without using constructor by Object.create()
  Square.prototype = Object.create(Shape.prototype); // inherit

  var s = new Square();
  console.log(s.draw()); // output > square
  console.log(s.AbstractMethodSize()) // output > 'must implement in sub class'

  // Let's implement method:
  Square.prototype.AbstractMethodSize = function() {
    return 'method implemented';
  console.log(s.AbstractMethodSize()) // Output > 'method implemented'

What is Concrete Class?

When a subclass extends an abstract class and it implements all the Abstract methods then this subclass is called a concrete class. It also has implementations of all methods of interfaces it implements.

Why 0.1 + 0.2 does not make 0.3?

JavaScript result is: 0.1 + 0.2 = 0.30000000000000004.
Because Integer data types store whole numbers, while float data types store fractional numbers.
It’s not a JS problem but a more general computer one. Floating numbers can’t store properly all decimal numbers, because they store stuff in binary

How to Fix: 
Number((0.1 +0.2).toFixed(2))

What is the difference between when we add a method using this and when we add by using Prototype?

Any method attached via “this” will get re-declared for every new instance we create, which could affect the memory usage of the application negatively if we wish to create so many instances.
Prototype will enable us to easily define methods for all instances and save memory. When creating methods with Prototype, a single instance of the method will flow to each object.

function Employee() { = 'jsmount';
    this.updateName = function(n) { = n;

Employee.prototype.replaceName = function() { = 'Programming';

var obj = new Employee();


Employee {name: "jsmount", updateName: ƒ}
name: "jsmount"
updateName: ƒ (n)
replaceName: ƒ ()
constructor: ƒ Employee()
__proto__: Object

What are the named class and unnamed class in JavaScript?

This is an anonymous class expression — you can’t refer to it by name within the class body.

const tech = class {
    name = 'JavaScript';
    printTech() {

This is a named class expression — you /can/ refer to this class by name within the class body

const myTech = class MyTech {
    name = 'java';
     //  Adding new method, to demonstrate we can refer to MyTech by name within the class . . . 
    printTech() {

How to find How many times a loop has been run?

We can use console.count to count this.

for (var i = 0; i < 10; i++){
    console.count('for loop');

This will give  output that loop has been run by 10 times.

When we execute a setInterval function it returns a value, what is that?

set interval

Whenever we execute the setInterval function, it returns an event Id that is used to clear that particular interval.

What is Callback?

A callback is a function that is passed to another function. When the first function is done, it will run the second function.

function getZoneDetails(id, callback) {
    if(id) {

getZoneDetails(12345, function() {
  // will execute after first function call

What are async and await?

JavaScript async await feature is used to overcome the Promise chaining. When we have a nested request within a request success and, within another request success, that is called the promise chaining.

Let’s see first Promise Chaining:

function drawShape(shape) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
        }, 1000)

function draw() {
    drawShape('circle').then(() => {
        return drawShape('square');
    }).then(() => {
        return drawShape('triangle')
    }).then(() => {
        return drawShape('image')


circle // it takes 1 second to log it
square // after first promise success
triangle // after second promise success
image  // after third promise success

Let’s rewrite the above code with async-await: MUCH EASIER AND CLEAN!!

async function draw() {
    await drawShape('circle');
    await drawShape('square');
    await drawShape('triangle');
    await drawShape('image');


read here for more info:

What is JavaScript V8 Engine? What is its use?

The V8 engine is open source engine written in C++ and designed by Google. This engine is used inside Google Chrome. Popular Node.js also uses this engine at runtime. So What is JavaScript Engine?
JavaScript Engine is a program that executes JavaScript Code. It works like an interpreter or a JIT compiler that compiles JS Code to byte Code.

Some Popular Engines are :

V8 — open-source
, developed by Google, written in C++
Rhino — managed by the Mozilla, open source, written in Java
SpiderMonkey — the first JavaScript engine, powered by Firefox
JavaScriptCore — open source, developed by Apple for Safari
Chakra (JScript9) — Internet Explorer

read here for more info

What is difference between event.stopImmediatePropagation(), event.propogation() and preventDefault()?

The preventDefault() method is used to prevent the browser from executing the default action of the selected element. There are several ways to add an event to a hyperlink element. Let’s look at some of them and use prevent default:

    <a href="" id="link" onclick="event.preventDefault()">Check prevent default
        Option 1</a>

    <a href="" id="link1" onclick="onClick()">Check prevent default Option 2</a>

    <a href="" id="link2">Check prevent default Option 3</a>

// By using event.preventDefault() - default behavior of a tag will not be executed. 
    function onClick() {
        alert('check prevented');

    var link = document.getElementById('link2');
    link.addEventListener('click', function (event) {
        alert('check prevented');


Prevents the event from bubbling up the DOM, but does not stop the browser’s default behavior.


It will prevent every event from running. It stops all next handler functions to be executed from where it was assigned.

var mydiv = document.getElementById('my-div');
  mydiv.addEventListener('click', function ($event) {
    alert('first executed');
  mydiv.addEventListener('click', function ($event) {
    alert('second execution will not happen');

What is the console.table?

Displaying JSON or very large JSON arrays inside a console.log is a terrifying experience. The console.table allows us to visualize these structures inside a beautiful table where we can name the columns and pass them as parameters.

Explain console.time?

Console.time starts a timer with a name specified as an input parameter, and can run up to 10,000 simultaneous timers on a given page. Once initiated, we use a call to console.timeEnd to stop the timer and print the elapsed time to the Console.

var arr =[];
for (var i = 0; i < 2000; i++){ 
    // do some stuff

 output > start: 0.27392578125ms

What is Blob? Write a simple program of Blob. How to read Blob data?

Blob means “Binary Large Object” which is responsible for holding data in the form of chunk of bytes. Content of a blob can be read as ArrayBuffer and therefore it makes blobs very handy to store binary data. Main purpose of ArrayBuffer is to keep binary data. This binary data can be of an image or a text file etc. A blob can be created using: the Blob() constructor.

var objData = {
    id: 11,
    name: 'mount',
    code: 'mount-89899',
    zone: 'IN'

// output will be of multiple lines because of null and 1 arguments
var jsonBlob = new Blob([JSON.stringify(objData, null, 1)], {type: 'application/json'}); 

//-- output is in single line
var jsonBlob = new Blob([JSON.stringify(objData)], {
    type: 'application/json'
function readBlobData() {
    var fileReader = new FileReader();
    fileReader.addEventListener('loadend', () => {
        console.log(fileReader.result); // will return result 
output > {"id":11,"name":"mount","code":"mount-89899","zone":"IN"}  






 ArrayBuffer(57) {} 

How to convert Blob into base64?

URL.createObjectURL is to convert a Blob into a base64-encoded string. To transform a Blob into base64, we’ll use the built-in FileReader object.

let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
let reader = new FileReader();
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload
reader.onload = function(){ return reader.result};


Write a program to download blob data as text file?

    <a id="blob-link" download="yourFilename">Download text file blob</a>
    var blob = new Blob(['this is testing blob site'], {type: 'text/plain' });
    var link = document.getElementById('blob-link');
    link.href = URL.createObjectURL(blob);


What are 5 Solid principles of Object Oriented Design with JavaScript?

S — Single responsibility principle
O — Open closed principle
L — Liskov substitution principle
I — Interface segregation principle
D — Dependency Inversion principle

S - Single responsibility principle
A class should have one and only one reason to change, meaning that a class should only have one job.

O — Open closed principle
Objects or entities should be open for extension, but closed for modification.
Open for extension means, We should write programs in a way that others can extend it and can add new features or components to the same application without breaking the existing code.
Close for modification means we should keep application code in a way that no other can modify in the existing code because that would force you to refactor a lot of existing code.

L — Liskov substitution principle
All this is stating is that every subclass/derived class should be substitutable for their base/parent class.

I — Interface segregation principle
This principle says that a class shouldn’t be forced to depend on methods they don’t use. Also a client (class or function) should never be forced to implement an interface which they don’t want to use.

D — Dependency Inversion principle
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

MAP VS Object ?

Map and Object both are used to store data in key-value pairs. This key value pair consists of a unique key and its value.

In object, the data-type of the key-field can be only of integer, string and symbol Whereas in Map, the key-field can be of any data-type. It may be an integer, array or an object as well.

In object order of element cannot be preserved while in the map the order of elements preserved.

Map is an instance of object.

var map = new Map();
map.set(4, {a: 1, b: 2, c: 3});
map.set('id', 23);

map.get(4) // output > {a: 1, b: 2, c: 3}
map.size // output 2
console.log(map instanceof Object); // true

// Below is simple Object
var obj = {name: 'jsmount', id: 3};

JavaScript Diff Between [] & ARRAY.length = 0 ?

var a = [5,4,3,6,1];
var b = ['r', 't'];

var c = a;
var d = b;

a = [];
b.length = 0;

console.log(a, b, c, d); 
//output > []    []    (5) [5, 4, 3, 6, 1]     []

= [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.

Array.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.

What is a factory function ?

In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.

Explain JavaScript Fetch API?

JavaScript is capable to send a request to server and fetch response of this request. It can load new information or data whenever is required by using AJAX (Asynchronous JavaScript And XML).

In old JavaScript we use ajax direct to communicate with server but in Modern JavaScript we have fetch() method to work on this.

let promise = fetch(url, [options])

url – the URL to access.
options – optional parameters: method, headers etc. So If we don't pass options it will be by default GET Request.
let url = 'your url';
let response = await fetch(url);

let commits = await response.json(); // read response body and parse as JSON
let user = {
  name: 'JS', id: 1

let response = await fetch('/save-user-api-url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  body: JSON.stringify(user)

let result = await response.json();

read here for more info on fetch API

Explain JavaScript arguments object?

arguments is default Array like object that is accessible inside a function and it contains values of passed argument to the function.

function print() {
	console.log(arguments[0], arguments[1]);

//output > Arguments(3) [4, 5, 6, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//output > 4 5

Define JavaScript Static keyword?

Static keyword defines a static method of the class. Static method are not called on instances of the classes. Instead of, they can be accessed only with class name.

class MyClass {
	getName() {
		return  'JS mount';
	static printName() {
		console.log('this is static method of class')

var obj = new MyClass();
obj.getName(); // output > JS mount
obj.printName() // output > Uncaught TypeError: obj.printName is not a function
MyClass.printName() // output > this is static method of classes

What is Virtual DOM?

DOM stands for Document Object Model and it is the structural text of a web page. Technically we say this text as HTML code and DOM is basically called HTML DOM. All the elements of HTML work as Node.
Can we have multiple DOM on a single Page?
Yes, we can have. As we can run multiple processes for the same program same as we can have multiple doms of the same HTML page (which means we are loading the same page in multiple tabs).

Now as we have SPA apps, DOM contains many and many divs and other elements, a number of events, and other handlers. So for any action, it reads from top to bottom every element and applies changes that lack app performance issues. To overcome this VIRTUAL DOM comes into action. Many developers think that Virtual DOM is developed by React but it’s not true.
One of the big advantages of Virtual dom is that it only reads and applies changes on the node where required and does not disturb any other element. React uses the concept of Virtual dom and all react elements lives in Virtual DOM.

What is JavaScript Max and Min Safest Number?

The MAX_SAFE_INTEGER constant has a value of 9007199254740991
We can remember this as (2 to the 53 – 1) => Math.pow(2,53) – 1
Same as MIN_SAFE_INTEGER is -(253 – 1) => -Math.pow(2, 53) – 1

Note: Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect.

The Number.isSafeInteger() method determines whether the provided value is a number that is a safe integer.
Number.isSafeInteger(Math.pow(2,53)) // output false

What is BigInt?

We can define a whole number larger than 2^53 – 1 (that is Number.MAX_SAFE_INTEGER) by the built-in object BigInt. BigInt can be used for arbitrarily large integers.

A BigInt is created by appending n to the end of an integer literal — 10n — or by calling the function BigInt().

Note: A BigInt is not strictly equal to a number, but it is loosely so:

0n === 0
// ↪ false

0n == 0
// ↪ true

Explain JavaScript FileReader?

Let’s first see the File constructor:
new File(fileParts, filename, [options]);
fileParts – is an array of Blob/BufferSource/String values.

We also get file instances from input type files:

<input type="file" onchange="readFile(this)">

function showFile(input) {
  let file = input.files[0];

File Reader is an object to read data from Blob. File object inherits from Blob so same is used to read File as well.

function readFile(input) {
  let file = input.files[0];
  let reader = new FileReader();
  reader.onload = function() {
  reader.onerror = function() {

Why [‘1’, ‘7’, ’11’].map(parseInt) returns [1, NaN, 3] in JavaScript?

parseInt syntax is : parseInt(value, radix); radix may be between 2 to 36.
parseInt(‘1’, 2) // output 1
parseInt(’11’, 2) // output 3

But in any case, If the radix value is not in the range of 2 to 36 it will give NaN.

let’s first expand our program :

['1', '7', '11'].map((val, index, arr) => parseInt(val, index, arr));

The First Iteration index is 0 and in the case of radix 0 (falsy value), it defaults set to 10.
The second Iteration index is 1 and value 7 does not exist with base 1 so it returns NaN.
The third Iteration index is 2 and the value 11 returns 3 on base 2 so it is 3.

Learn more JavaScript Interview questions : Click here
Click here to read top Typescript questions.

JavaScript Top Interview questions
JavaScript Top Interview questions

Leave a Reply

Your email address will not be published.