Javascript Interview Questions

Basic JS questions :

1. What are the different data types present in JavaScript?
2. Explain Hoisting in JavaScript.
3. Difference between “==” and “===” operators.
4. Explain Implicit Type Coercion in JavaScript.
5. Is JavaScript a statically typed or a dynamically typed language?
6. What is NaN property in JavaScript?
7. What is an Immediately Invoked Function in JavaScript?
8. Explain Higher Order Functions in JavaScript.
9. Explain “this” keyword.
10. Explain call(), apply() and, bind() methods.
11. What is Currying in JavaScript?
12. Explain Scope and Scope Chain in JavaScript.
13. Explain Closures in JavaScript.
14. What are object prototypes?
15. What are callbacks?
16. What is memorization?
17. What is recursion in a programming language?
18. What is the use of a constructor function in JavaScript?
19. What is DOM?
20. What are arrow functions?
21. Differences between declaring variables using var, let and const.
22. What is the rest parameter and spread operator?
23. What is the use of promises in JavaScript?
24. What are classes in JavaScript?
25. What are generator functions?
26. Explain WeakSet in JavaScript.
27. Explain WeakMap in JavaScript.
28. What is Object Destructuring?
29. What is a Temporal Dead Zone?

Primitive types :

String :  A string will be represented using a single or a double quote. It will also represents a series of characters.

let a= "Rohit Gautam"; //using double quotes
let b= 'Ajit Singh'; //using single quotes

Number – It will represent a number and can be written with or without decimals.

let a = 3; // Without decimal
let b = 3.6; // With decimal

BigInt – The number which is above the limitation of Number data type, BigInt store that number. It can store large integers and is represented by adding “n” to an integer literal.

const bigInt =  90123456789023452345678678901230145678923234;

Boolean – It will have only two values : true or false. Booleans are generally used for conditional testing in any application.

let a = 7;
let b =  7;
let c =  4;
let d =  4;
(a == b) // returns true
(a == c) //returns false
(c == d) //returns true

Undefined – When any value is not assigned to a declared variable, it will have the value of undefined and it’s type is also undefined.

var a; // value of a is undefined
var b = undefined; // we can also set the value of a variable as undefined

Null – It represents a non-existent or a invalid value.

var a = null;

Symbol – It is a new data type which is introduced in the ES6 version of JavaScript. It is used to store an unique value.

let a = Symbol('symbol');

typeof of primitive types :

typeof "Ajit Singh" // Returns "string"
typeof 34.4 // Returns "number"
typeof true // Returns "boolean"
typeof 21234567890123453456789012345678906789012345678901234567890 // Returns bigint
typeof undefined // Returns "undefined"
typeof null // Returns "object" (It is a bug in JavaScript)
typeof Symbol('symbol') // Returns Symbol

Non-primitive types : 

As we have used Primitive data types can store only a single value. To store multiple values, non-primitive data types will be used.

Object – Used to store collection of data.

// Collection of data in form of key-value pairs

var object1 = {
   a:  12,
   b:  "JavaScript",
   c: function(){
      return this.a;
// Collection of data as an ordered list
var arr1 = [9, "JavaScript", true, 5.5, false];

2. Explain Hoisting in JavaScript.

Hoisting is a default way of JavaScript where all the variable and function declarations are continued on top.

This means variables and functions are declared, they will moved on top of the scope. The scope can be both local and global.

hoistedVariable = 6;
console.log(hoistedVariable); // outputs 6 even when the variable is declared after it is initialized	
var hoistedVariable;
var a = 2021;
var b = "Online Portfolio";
a + b    // Returns "2021Online Portfolio";



These both are the comparison operators where ‘==’ only compare value whereas, ‘===’ used to compare both value and type.

var a = 5;
var b = "5";
(a == b)  // Returns true since the value of both a and b is the same

(a === b) // Returns false since the typeof a is "number" and typeof b is "string"

4. Explain Implicit Type Coercion in JavaScript.

Implicit type coercion in JavaScript is process of automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.

String coercion :

While using the ‘ + ‘ operator between 2 different value. When a number is added to a string, the number type is always converted to the string type.

var a = 21;
var b = "online-portoflioin";
a + b   // Returns "21Helloonline-portoflioin";

5. Is JavaScript a statically typed or a dynamically typed language?

It is a dynamically typed language and  the type of a variable is checked during run-time in contrast to statically typed language, where the type of a variable is checked during compile-time.

Since JavaScript is a loosely(dynamically) composed language, factors in JS are not related with any sort. A variable can hold the worth of any information type.

For instance, a variable which is alloted a number kind can be changed over to a string type:

var a = 13;
var a = "online-portfolioin";

6. What is NaN property in JavaScript?

NaN stands for Not a Number, It will check if value is not a legal number. NaN type return number, To check if a value is NaN, we use the isNaN() function.

isNaN("onlineportfolio")  // Returns true
isNaN(555)   // Returns false
isNaN('10')  // Returns false, since '10' is converted to Number type which results in 0 ( a number) 
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true

7. What is an Immediately Invoked Function in JavaScript?

Syntax of IIFE :

{ // Do something; })();

To understand IIFE, we need to understand the two sets of parentheses which are added while creating an IIFE :

First set of parenthesis:

(function (){ //Do something; })

While executing JavaScript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

function() {
  //Do something;
// Compiler gives an error since the syntax of declaring a function is wrong in the code above.

To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.

Second set of parenthesis:

(function (){
  //Do something;
From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:

(function (){ // Do something; }) // Returns the function declaration
Therefore to invoke the function, we use the second set of parenthesis. . 

9. Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

Higher order functions are a result of functions being first-class citizens in javascript.

Examples of higher order functions:

function higherOrder(fn) {
higherOrder(function() { console.log("Hello world") }); 
function higherOrder2() {
  return function() {
    return "Do something";
var x = higherOrder2();
x()   // Returns "Do something"

10. Explain “this” keyword.

The “this” keyword refers to the object that the function is a property of.

The value of “this” keyword will always depend on the object that is invoking the function.

Confused? Let’s understand the above statements by examples:

function doSomething() {

What do you think the output of the above code will be?

**Note – Observe the line where we are invoking the function.

Check the definition again:

The “this” keyword refers to the object that the function is a property of.

In the above code, function is a property of which object?

Since the function is invoked in the global context, the function is a property of the global object.

Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.

Example 2:

var obj = {
    name:  "vivek",
    getName: function(){

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.

Example 3:

 var obj = {
    name:  "vivek",
    getName: function(){
var getName = obj.getName;
var obj2 = {name:"akshay", getName };

Can you guess the output here?

The output will be “akshay”.

Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .

The silly way to understanding the this keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot .

If there is no object before the dot like in example1, the value of this keyword will be the global object.

Example 4:

var obj1 = {
    address : "Mumbai,India",
    getAddress: function(){
var getAddress = obj1.getAddress;
var obj2 = {name:"akshay"};

Can you guess the output?

The output will be an error.

Although in the code above, the this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.

11. Explain call(), apply() and, bind() methods.

call()It’s a predefined method in javascript.

This method invokes a method (function) by specifying the owner object.

Example 1:

function sayHello(){
  return "Hello " +;
var obj = {name: "Sandy"};;
// Returns "Hello Sandy"

call() method allows an object to use the method (function) of another object.

Example 2:

var person = {
  age: 23,
  getAge: function(){
    return this.age;
var person2 = {age:  54};;
// Returns 54  

call() accepts arguments:

function saySomething(message){
  return + " is " + message;
var person4 = {name:  "John"};, "awesome");
// Returns "John is awesome"    


The apply method is similar to the call() method. The only difference is that,

call() method takes arguments separately whereas, apply() method takes arguments as an array.

function saySomething(message){
  return + " is " + message;
var person4 = {name:  "John"};
saySomething.apply(person4, ["awesome"]);


This method returns a new function, where the value of “this” skeyword will be bound to the owner object, which is provided as a parameter.

Example with arguments:

var bikeDetails = {
    displayDetails: function(registrationNumber,brandName){
    return " , "+ "bike details: "+ registrationNumber + " , " + brandName;
var person1 = {name:  "Vivek"};
var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");
// Binds the displayDetails function to the person1 object
// Returns Vivek, bike details: TS0452, Thunderbird

12. What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or less arguments.Example of a curried function:

function add (a) {
  return function(b){
    return a + b;


For Example, if we have a function f(a,b) , then the function after currying, will be transformed to f(a)(b).

By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.

Let’s see currying in action:

function multiply(a,b){
  return a*b;

function currying(fn){
  return function(a){
    return function(b){
      return fn(a,b);

var curriedMultiply = currying(multiply);

multiply(4, 3); // Returns 12

curriedMultiply(4)(3); // Also returns 12

As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply , which takes in one parameter at a time.

13. Explain Scope and Scope Chain in javascript.

Scope in JS, determines the accessibility of variables and functions at various parts in one’s code.

In general terms, the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access.

There are three types of scopes in JS:

  • Global Scope
  • Local or Function Scope
  • Block Scope

Global Scope

Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code

var globalVariable = "Hello world";

function sendMessage(){
  return globalVariable; // can access globalVariable since it's written in global space

function sendMessage2(){
  return sendMessage(); // Can access sendMessage function since it's written in global space

sendMessage2();  // Returns “Hello world”

Function Scope

Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.

function awesomeFunction(){
  var a = 2;

  var multiplyBy2 = function(){
    console.log(a*2); // Can access variable "a" since a and multiplyBy2 both are written inside the same function
console.log(a); // Throws reference error since a is written in local scope and cannot be accessed outside

multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope

Block Scope

Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope.

Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.

  let x = 45;

console.log(x); // Gives reference error since x cannot be accessed outside of the block

for(let i=0; i<2; i++){
  // do something

console.log(i); // Gives reference error since i cannot be accessed outside of the for loop block

Scope Chain

JavaScript engine also uses Scope to find variables.

Let’s understand that using an example:

var y = 24;

function favFunction(){
  var x = 667;
  var anotherFavFunction = function(){
    console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside favFunction, outputs 667

  var yetAnotherFavFunction = function(){
    console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable inside favFunction and does not find it, so looks for variable in global scope, finds it and outputs 24



As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.

If the variable is not found in the global space as well, reference error is thrown.

14. Explain Closures in JavaScript.

Closures is an ability of a function to remember the variables and functions that are declared in its outer scope.

var Person = function(pName){
  var name = pName;

  this.getName = function(){
    return name;

var person = new Person("Neelesh");

Let’s understand closures by example:

function randomFunc(){
  var obj1 = {name:"Vivian", age:45};

  return function(){
    console.log( + " is "+ "awesome"); // Has access to obj1 even when the randomFunc function is executed


var initialiseClosure = randomFunc(); // Returns a function


Let’s understand the code above,

The function randomFunc() gets executed and returns a function when we assign it to a variable:

var initialiseClosure = randomFunc();

The returned function is then executed when we invoke initialiseClosure:


The line of code above outputs “Vivian is awesome” and this is possible because of closure.

When the function randomFunc() runs, it sees that the returning function is using the variable obj1 inside it:

console.log( + " is "+ "awesome");

Therefore randomFunc(), instead of destroying the value of obj1 after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed.

This ability of a function to store a variable for further reference even after it is executed, is called Closure.

15. What are object prototypes?

All javascript objects inherit properties from a prototype.

For example,

Date objects inherit properties from the Date prototype

Math objects inherit properties from the Math prototype

Array objects inherit properties from the Array prototype.

On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.

A prototype is a blueprint of an object. Prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

var arr = [];

console.log(arr); // Outputs [2]

In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.

The reason being the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype’s prototype and so on.

16. What are callbacks?

A callback is a function that will be executed after another function gets executed.

In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function and can be used as a property of an object.

Functions that are used as an argument to another function are called callback functions.


function divideByHalf(sum){
  console.log(Math.floor(sum / 2));

function multiplyBy2(sum){
  console.log(sum * 2);

function operationOnSum(num1,num2,operation){
  var sum = num1 + num2;

operationOnSum(3, 3, divideByHalf); // Outputs 3

operationOnSum(5, 5, multiplyBy2); // Outputs 20

In the code above, we are performing mathematical operations on the sum of two numbers.

The operationOnSum function takes 3 arguments, first number, second number, and the operation that is to be performed on their sum (callback) .

Both divideByHalf and multiplyBy2 functions are used as callback functions in the code above.

These callback functions will be executed only after the function operationOnSum is executed.

Therefore, callback is a function that will be executed after another function gets executed.

17.What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.

Let’s understand memoization, by converting a simple function to a memoized function:

**Note- Memoization is used for expensive function calls but in the following example, we are considering a simple function for understanding the concept of memoization better.

Consider the following function:

function addTo256(num){
  return num + 256;

addTo256(20); // Returns 276
addTo256(40); // Returns 296
addTo256(20); // Returns 276

In the code above, we have written a function that adds the parameter to 256 and returns it.

When we are calling the function addTo256 again with the same parameter (“20” in the case above), we are computing the result again for the same parameter.

Computing the result with the same parameter again and again is not a big deal in the above case, but imagine if the function does some heavy duty work, then, computing the result again and again with the same parameter will lead to wastage of time.

This is where memoization comes in, by using memoization we can store(cache) the computed results based on the parameters. If the same parameter is used again while invoking the function, instead of computing the result, we directly return the stored (cached) value.

Let’s convert the above function addTo256, to a memoized function:

function memoizedAddTo256(){
  var cache = {};

  return function(num){
    if(num in cache){
      console.log("cached value");
      return cache[num]

      cache[num] = num + 256;
      return cache[num];

var memoizedFunc = memoizedAddTo256();

memoizedFunc(20); // Normal return
memoizedFunc(20); // Cached return

In the code above, if we run memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.

**Note- Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

18. What is recursion in a programming language?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

function add(number) {
  if (number <= 0) {
    return 0;
  } else {
    return number + add(number - 1);

add(3) => 3 + add(2)
          3 + 2 + add(1)
          3 + 2 + 1 + add(0)
          3 + 2 + 1 + 0 = 6  

Example of a recursive function:

The following function calculates the sum of all the elements in an array by using recursion:

function computeSum(arr){
  if(arr.length === 1){
    return arr[0];
    return arr.pop() + computeSum(arr);

computeSum([7, 8, 9, 99]); // Returns 123

19. What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor functions are used.

**Note- Name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.


function Person(name,age,gender){ = name;
  this.age = age;
  this.gender = gender;

var person1 = new Person("Vivek", 76, "male");

var person2 = new Person("Courtney", 34, "female");

In the code above, we have created a constructor function named Person.

Whenever we want to create a new object of the type Person,

We need to create it using the new keyword:

var person3 = new Person("Lilly", 17, "female");

The above line of code will create a new object of the type Person.

Constructor functions allow us to group similar objects.

20. What is DOM?

DOM stands for Document Object Model.

DOM is a programming interface for HTML and XML documents.

When the browser tries to render a HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.

Example of how HTML code gets converted to DOM:

Advanced Javascript Interview Questions:


21. What are arrow functions?

Arrow functions were introduced in the ES6 version of javascript.

They provide us with a new and shorter syntax for declaring functions.

Arrow functions can only be used as a function expression.

Let’s compare the normal function declaration and the arrow function declaration in detail:

// Traditional Function Expression
var add = function(a,b){
  return a + b;

// Arrow Function Expression
var arrowAdd = (a,b) => a + b;

Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces { } can be omitted.

// Traditional function expression
var multiplyBy2 = function(num){
  return num * 2;
// Arrow function expression
var arrowMultiplyBy2 = num => num * 2;

If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above.

var obj1 = {
  valueOfThis: function(){
    return this;
var obj2 = {
  valueOfThis: ()=>{
    return this;

obj1.valueOfThis(); // Will return the object obj1
obj2.valueOfThis(); // Will return window/global object

The biggest difference between the traditional function expression and the arrow function, is the handling of the this keyword.

By general definition, the this keyword always refers to the object that is calling the function.

As you can see in the code above, obj1.valueOfThis() returns obj1, since this keyword refers to the object calling the function.

In the arrow functions, there is no binding of the this keyword.

The this keyword inside an arrow function, does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case.

Therefore, in the code above, obj2.valueOfThis() returns the window object.

22. Differences between declaring variables using var, let and const.

Before the ES6 version of javascript, only the keyword var was used to declare variables.

With the ES6 Version, keywords let and const were introduced to declare variables.

keyword const let var
global scope no no yes
function scope yes yes yes
block scope yes yes no
can be reassigned no yes yes

Let’s understand the differences with examples:

Let’s understand the differences with examples:

var variable1 = 23;

let variable2 = 89;

function catchValues(){

// Both the variables can be accessed anywhere since they are declared in the global scope

window.variable1; // Returns the value 23

window.variable2; // Returns undefined    

The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.

Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.

But, there is one difference !

Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName.

Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.

var vs let in functional scope

function varVsLetFunction(){
  let awesomeCar1 = "Audi";
  var awesomeCar2 = "Mercedes";

console.log(awesomeCar1); // Throws an error
console.log(awesomeCar2); // Throws an error

Variables declared in a functional/local scope using var and let keywords behave exactly the same, meaning , they cannot be accessed from outside of the scope.

  var variable3 = [1, 2, 3, 4];

console.log(variable3); // Outputs [1,2,3,4]

  let variable4 = [6, 55, -1, 2];

console.log(variable4); // Throws error

for(let i = 0; i < 2; i++){
  //Do something

console.log(i); // Throws error

for(var j = 0; j < 2; i++){
  // Do something

console.log(j) // Outputs 2

In javascript, a block means the code written inside the curly braces {} .

Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.

Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.

Const keyword

Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.


const x = {name:"Vivek"};

x = {address: "India"}; // Throws an error = "Nikhil"; // No error is thrown

const y = 23;

y = 44; // Throws an error

In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.

23. What is the rest parameter and spread operator?

Both rest parameter and spread operator were introduced in the ES6 version of javascript.

Rest parameter ( … )

It provides an improved way of handling parameters of a function.

Using the rest parameter syntax, we can create functions that can take a variable number of arguments.

Any number of arguments will be converted into an array using the rest parameter.

It also helps in extracting all or some parts of the arguments.

Rest parameter can be used by applying three dots (…) before the parameters.

function extractingArgs(...args){
  return args[1];

// extractingArgs(8,9,1); // Returns 9

function addAllArgs(...args){
  let sumOfArgs = 0;
  let i = 0;
  while(i < args.length){
    sumOfArgs += args[i];
  return sumOfArgs;

addAllArgs(6, 5, 7, 99); // Returns 117
addAllArgs(1, 3, 4); // Returns 8

**Note- Rest parameter should always be used at the last parameter of a function:

// Incorrect way to use rest parameter
function randomFunc(a,...args,c){
//Do something

// Correct way to use rest parameter
function randomFunc2(a,b,...args){
//Do something

Spread operator (…)

Although the syntax of spread operator is exactly the same as the rest parameter, spread operator is used to spread an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.

function addFourNumbers(num1,num2,num3,num4){
  return num1 + num2 + num3 + num4;

let fourNumbers = [5, 6, 7, 8];

// Spreads [5,6,7,8] as 5,6,7,8

let array1 = [3, 4, 5, 6];
let clonedArray1 = [...array1];
// Spreads the array into 3,4,5,6
console.log(clonedArray1); // Outputs [3,4,5,6]

let obj1 = {x:'Hello', y:'Bye'};
let clonedObj1 = {...obj1}; // Spreads and clones obj1

let obj2 = {z:'Yes', a:'No'};
let mergedObj = {...obj1, ...obj2}; // Spreads both the objects and merges it
// Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'};

***Note- Key differences between rest parameter and spread operator:

  • Rest parameter is used to take a variable number of arguments and turns into an array while the spread operator takes an array or an object and spreads it
  • Rest parameter is used in function declaration whereas the spread operator is used in function calls.

24. What is the use of promises in javascript?

Promises are used to handle asynchronous operations in javascript.

Before promises, callbacks were used to handle asynchronous operations. But due to limited functionality of callback, using multiple callbacks to handle asynchronous code can lead to unmanageable code.

Promise object has four states –

  • Pending – Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  • Fulfilled – This state represents that the promise has been fulfilled, meaning the async operation is completed.
  • Rejected – This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  • Settled – This state represents that the promise has been either rejected or fulfilled.

A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

resolve is a function that will be called, when the async operation has been successfully completed.

reject is a function that will be called, when the async operation fails or if some error occurs.

Example of a promise:

Promises are used to handle asynchronous operations like server requests, for the ease of understanding, we are using an operation to calculate the sum of three elements.

In the function below, we are returning a promise inside a function:

function sumOfThreeElements(...elements){
  return new Promise((resolve,reject)=>{
    if(elements.length > 3 ){
      reject("Only three elements or less are allowed");
      let sum = 0;
      let i = 0;
      while(i < elements.length){
        sum += elements[i];
      resolve("Sum has been calculated: "+sum);

In the code above, we are calculating the sum of three elements, if the length of elements array is more than 3, promise is rejected, else the promise is resolved and the sum is returned.

We can consume any promise by attaching then() and catch() methods to the consumer.

then() method is used to access the result when the promise is fulfilled.

catch() method is used to access the result/error when the promise is rejected.

In the code below, we are consuming the promise:

sumOfThreeElements(4, 5, 6)
.then(result=> console.log(result))
.catch(error=> console.log(error));
// In the code above, the promise is fulfilled so the then() method gets executed

sumOfThreeElements(7, 0, 33, 41)
.then(result => console.log(result))
.catch(error=> console.log(error));
// In the code above, the promise is rejected hence the catch() method gets executed

25.What are classes in javascript?

Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions.

They provide a new way of declaring constructor functions in javascript.

Below are the examples of how classes are declared and used:

// Before ES6 version, using constructor functions
function Student(name,rollNumber,grade,section){ = name;
  this.rollNumber = rollNumber;
  this.grade = grade;
  this.section = section;

// Way to add methods to a constructor function
Student.prototype.getDetails = function(){
  return 'Name: ${}, Roll no: ${this.rollNumber}, Grade: ${this.grade}, Section:${this.section}';

let student1 = new Student("Vivek", 354, "6th", "A");
// Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A

// ES6 version classes
class Student{
  constructor(name,rollNumber,grade,section){ = name;
    this.rollNumber = rollNumber;
    this.grade = grade;
    this.section = section;

  // Methods can be directly added inside the class
    return 'Name: ${}, Roll no: ${this.rollNumber}, Grade:${this.grade}, Section:${this.section}';

let student2 = new Student("Garry", 673, "7th", "C");
// Returns Name: Garry, Roll no:673, Grade: 7th, Section:C

Key points to remember about classes:

  • Unlike functions, classes are not hoisted. A class cannot be used before it is declared.
  • A class can inherit properties and methods from other classes by using the extend keyword.
  • All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. Error will be thrown if the strict mode rules are not followed.

26. What are generator functions?

Introduced in ES6 version, generator functions are a special class of functions.

They can be stopped midway and then continue from where it had stopped.

Generator functions are declared with the function* keyword instead of the normal function keyword:

function* genFunc(){
  // Perform operation

In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:

function normalFunc(){
  return 22;
  console.log(2); // This line of code does not get executed

In the case of generator functions, when called, they do not execute the code, instead they return a generator object . This generator object handles the execution.

function* genFunc(){
  yield 3;
  yield 4;
genFunc(); // Returns Object [Generator] {}

The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value.

For example if we run the next() method on the above code:

genFunc().next(); // Returns {value: 3, done:false}

As one can see the next method returns an object consisting of value and done properties.
Value property represents the yielded value.
Done property tells us whether the function code is finished or not. (Returns true if finished)
Generator functions are used to return iterators. Let’s see an example where an iterator is returned:

function* iteratorFunc() {
  let count = 0;
  for (let i = 0; i < 2; i++) {
      yield i;
  return count;

let iterator = iteratorFunc();
console.log(; // {value:0,done:false}
console.log(; // {value:1,done:false}
console.log(; // {value:2,done:true}

As you can see in the code above, the last line returns done:true , since the code reaches the return statement.

27. Explain WeakSet in javascript.

In javascript, Set is a collection of unique and ordered elements.

Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:

  • Weakset contains only objects and no other type.
  • An object inside the weakset is referenced weakly. This means, if the object inside the weakset does not have a reference, it will be garbage collected.
  • Unlike Set, WeakSet only has three methods, add() delete() and has() .
const newSet = new Set([4, 5, 6, 7]);
console.log(newSet);// Outputs Set {4,5,6,7}

const newSet2 = new WeakSet([3, 4, 5]); //Throws an error

let obj1 = {message:"Hello world"};
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true

28. Explain WeakMap in javascript.

In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types.

WeakMap is similar to Map with key differences:

  • The keys and values in weakmap should always be an object.
  • If there are no references to the object, the object will be garbage collected.
const map1 = new Map();
map1.set('Value', 1);

const map2 = new WeakMap();
map2.set('Value', 2.3); // Throws an error

let obj = {name:"Vivek"};
const map3 = new WeakMap();
map3.set(obj, {age:23});

29. What is Object Destructuring?

Object destructuring is a new way to extract elements from an object or an array.

Object destructuring:

Before ES6 version:

const classDetails = {
  strength: 78,
  benches: 39,

const classStrength = classDetails.strength;
const classBenches = classDetails.benches;
const classBlackBoard = classDetails.blackBoard;

The same example using object destructuring:

const classDetails = {
  strength: 78,
  benches: 39,

const {strength:classStrength, benches:classBenches,blackBoard:classBlackBoard} = classDetails;

console.log(classStrength); // Outputs 78
console.log(classBenches); // Outputs 39
console.log(classBlackBoard); // Outputs 1

As one can see, using object destructuring we have extracted all the elements inside an object in one line of code.

If we want our new variable to have the same name as the property of an object we can remove the colon:

const {strength:strength} = classDetails;
// The above line of code can be written as:
const {strength} = classDetails;

Array destructuring:

Before ES6 version:

const arr = [1, 2, 3, 4];
const first = arr[0];
const second = arr[1];
const third = arr[2];
const fourth = arr[3];

The same example using object destructuring:

const arr = [1, 2, 3, 4];
const [first,second,third,fourth] = arr;

console.log(first); // Outputs 1
console.log(second); // Outputs 2
console.log(third); // Outputs 3
console.log(fourth); // Outputs 4

30. What is a Temporal Dead Zone?

Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords.

It is a behaviour where we try to access a variable before it is initialized.

Examples of temporal dead zone:

x = 23; // Gives reference error

let x;

function anotherRandomFunc(){
  message = "Hello"; // Throws a reference error

  let message;

In the code above, both in global scope and functional scope, we are trying to access variables which have not been declared yet. This is called the Temporal Dead Zone .

Coding problems:


31. Guess the outputs of the following codes:

// Code 1:

function func1(){

  var x = 2;
  let y = 12;


// Code 2:

function func2(){
  for(var i = 0; i < 3; i++){
    setTimeout(()=> console.log(i),2000);



// Code 3:

  setTimeout(()=> console.log(1),2000);
  setTimeout(()=> console.log(3),0);


Code 1 – Outputs and 12 . Since, even though let variables are not hoisted, due to async nature of javascript, the complete function code runs before the setTimeout function. Therefore, it has access to both x and y.

Code 2 – Outputs , three times since variable declared with var keyword does not have block scope. Also, inside the for loop, the variable i is incremented first and then checked.

Code 3 – Output in the following order:

1 // After two seconds

Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API and therefore, the complete function executes before the setTimeout function can execute.

32.Guess the outputs of the following code:

// Code 1:

let x= {}, y = {name:"Ronny"},z = {name:"John"};

x[y] = {name:"Vivek"};
x[z] = {name:"Akki"};


// Code 2:

function runFunc(){
  console.log("1" + 1);
  console.log("A" - 1);
  console.log(2 + "-2" + "2");
  console.log("Hello" - "World" + 78);
  console.log("Hello"+ "78");


// Code 3:

let a = 0;
let b = false;
console.log((a == b));
console.log((a === b));


Code 1 – Output will be {name: “Akki”}.

Adding objects as properties of another object should be done carefully.

Writing x[y] = {name:”Vivek”} , is same as writing x[‘object Object’] = {name:”Vivek”} ,

While setting a property of an object, javascript coerces the parameter into a string.

Therefore, since is an object, it will be converted to ‘object Object’.

Both x[y] and x[z] are referencing the same property.

Code 2 – Outputs in the following order:


Code 3 – Output in the following order due to equality coercion:


33. Guess the output of the following code:

var x = 23;

  var x = 43;
  (function random(){
    var x = 21;


Output is NaN .

random() function has functional scope, since x is declared and hoisted in the functional scope.

Rewriting the random function will give a better idea about the output:

function random(){
  var x; // x is hoisted
  x++; // x is not a number since it is not initialized yet
  console.log(x); // Outputs NaN
  x = 21; // Initialization of x

34. Guess the outputs of the following code:

// Code 1

  let hero = {
    powerLevel: 99,
      return this.powerLevel;
  let getPower = hero.getPower;
  let hero2 = {powerLevel:42};
  // Code 2
  const a = function(){
    const b = {
      func1: function(){
    const c = {
      func2: ()=>{
  // Code 3
  const b = {
    f: function(){
      var self = this;


Code 1 – Output in the following order:


Reason – The first output is undefined since when the function is invoked, it is invoked referencing the global object:

window.getPower() = getPower();

Code 2 – Outputs in the following order:

global/window object
object "b"
global/window object

Since we are using arrow function inside func2, this keyword refers to the global object.

Code 3 – Outputs in the following order:


Only in the IIFE inside the function , the this keyword refers to the global/window object.

35. Guess the outputs of the following code:

**Note – Code 2 and Code 3 require you to modify the code, instead of guessing the output.

// Code 1

  return (function(){
    a = 23;

// Code 2

// Each time bigFunc is called, an array of size 700 is being created,
// Modify the code so that we don't create the same array again and again

function bigFunc(element){
  let newArray = new Array(700).fill('♥');
  return newArray[element];

console.log(bigFunc(599)); // Array is created
console.log(bigFunc(670)); // Array is created again

// Code 3

// The following code outputs 2 and 2 after waiting for one second
// Modify the code to output 0 and 1 after one second.

function randomFunc(){
  for(var i = 0; i < 2; i++){
    setTimeout(()=> console.log(i),1000);


Answers –

Code 1 – Outputs 45 .

Even though a is defined in the outer function, due to closure the inner functions have access to it.

Code 2 – This code can be modified by using closures,

function bigFunc(){
  let newArray = new Array(700).fill('♥');
  return (element) => newArray[element];

let getElement = bigFunc(); // Array is created only once

Code 3 – Can be modified in two ways:

Using let keyword:

function randomFunc(){
  for(let i = 0; i < 2; i++){
    setTimeout(()=> console.log(i),1000);


Using closure:

function randomFunc(){
  for(var i = 0; i < 2; i++){


36. Write a function that performs binary search on a sorted array.


function binarySearch(arr,value,startPos,endPos){
  if(startPos > endPos) return -1;

  let middleIndex = Math.floor(startPos+endPos)/2;

  if(arr[middleIndex] === value) return middleIndex;

  elsif(arr[middleIndex > value]){
    return binarySearch(arr,value,startPos,middleIndex-1);
    return binarySearch(arr,value,middleIndex+1,endPos);

37. Implement a function that returns an updated array with right rotations on an array of integers .


Given the following array:


Perform right rotations:

First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]

return [4,5,7,2,3]


function rotateRight(arr,rotations){
  if(rotations == 0) return arr;
  for(let i = 0; i < rotations;i++){
    let element = arr.pop();

  return arr;

rotateRight([2, 3, 4, 5, 7], 3); // Return [4,5,7,2,3]
rotateRight([44, 1, 22, 111], 5); // Returns [111,44,1,22]

JavaScript Methods

JavaScript Methods

JavaScript Methods : In JavaScript, there are many implicit techniques. For instance, Here, the parseInt() method of the Number article is utilized to change over numeric string worth to a whole number worth. To get familiar with worked-in strategies, visit JavaScript Built-In Methods.

Perhaps you don’t care for bolt works, you would prefer not to invest an excess of energy discovering some new information, or they’re simply not important for you. Relax, you are in good company. I’ll show you how it is done in ES5 (practical deceleration) and ES6 (bolt works).

Know: Arrow capacities and capacity statements/articulations are not same and can’t be supplanted aimlessly. Remember that the this watchword works diversely between the two.

How to use Method

Item Methods in JavaScript can be gotten to by utilizing capacities. Capacities in JavaScript are put away as property estimations. The items can likewise be called without utilizing section (). In a technique, ‘this’ alludes to the proprietor object. Extra data can likewise be added alongside the article technique. Language structure: objectName.methodName()


const a = ["Rohit Gautam", "Ajit"];
const b = ["Sandeep", "Alok", "Ankit"];
const c = ["Amit"];
const children = a.concat(b, c);
// Output 
(6) ["Rohit Gautam", "Ajit", "Sandeep", "Alok", "Ankit", "Amit"]


const persons = ["Rohit Gautam", "Ajit", "Alok", "Ankit"];
const copy = persons.copyWithin(2, 0);

(4) ["Rohit Gautam", "Ajit", "Rohit Gautam", "Ajit"]

entries() :

The Array.entries() method returns an Array Iterator object with key/value pairs:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {

Array Iterator {}
[0, "Banana"]
[1, "Orange"]
[2, "Apple"]
[3, "Mango"]


Check if all the values in number[] are 10 or greater:

 const number= [32, 33, 16, 40];

 function checkNumber(age) {
 return age > 10;



const fruits = ["Banana", "Orange", "Apple", "Mango"];


const ages = [32, 33, 16, 40];


function checkAdult(age) {
  return age >= 18;


const ages = [3, 10, 18, 20];

function checkAge(age) {
  return age > 18;

function myFunction() {



const ages = [3, 10, 18, 20];


function checkAge(age) {
  return age > 18;


let text = "";
const fruits = ["apple", "orange", "cherry"];

function myFunction(item, index) {
  text += index + ": " + item + "<br>"; 
0: apple
1: orange
2: cherry


const myArr = Array.from("ABCDEFG");


const fruits = ["Banana", "Orange", "Apple", "Mango"];


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.indexOf("Apple")   // Returns 2


const fruits = ["Banana", "Orange", "Apple", "Mango"];
Array.isArray(fruits)   // Returns true


const fruits = ["Banana", "Orange", "Apple", "Mango"];
// output


const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();

let text = "";
for (let x of keys) {
  text += x + "<br>";
console.log(text );


const fruits = ["Apple", "Orange", "Apple", "Mango"];
fruits.lastIndexOf("Apple")   ;



const numbers = [4, 9, 16, 25];


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();   // Removes "Mango"

"Banana", "Orange", "Apple"


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");   // Adds "Kiwi"



const numbers = [275, 50, 25];


function myFunc(total, num) {
  return total - num;



const numbers = [175, 50, 25];


function myFunc(total, num) {
  return total - num;


const fruits = ["Banana", "Orange", "Apple", "Mango"];


const fruits = ["Banana", "Orange", "Apple", "Mango"];


const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);


const ages = [3, 10, 18, 20];

ages.some(checkAdult)   // Returns true

function checkAdult(age) {
  return age >= 18;


const fruits = ["Banana", "Orange", "Apple", "Mango"];


const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At position 2, add 2 elements: 
fruits.splice(2, 0, "Lemon", "Kiwi");



const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.toString();


const fruits = ["Banana", "Orange", "Apple", "Mango"];


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.valueOf();   // Returns fruits


How to remove duplicates from an array of objects using JavaScript?

How to remove duplicates from an array of objects using JavaScript? : Given an assortment of articles and the task is to dispose of the duplicate item part from the group list. There are two procedures to deal with this issue which are discussed below :

Strategy 1:

Using one of the keys as index: A temporary array is created which stores the objects of the original array using one of its keys as the index. Anyone of the object properties can be used as a key. The key is extracted from the object and used as the index of the new temporary array. The object is then assigned to this index. This approach will remove the duplicate objects as only one of each object of the original array will get assigned to the same index.

<!DOCTYPE html>

        How to remove duplicates from an array of objects using JavaScript ?

    <h1 style="color: green">
        Online Portfolio

        How to remove duplicates from an array of objects?

        Click on the button to remove the duplicated in the array

    <p>Check the console for the output</p>

    <button onclick="deleteDuplicates()">
        Remove Duplicate

    <script type="text/javascript">
        function deleteDuplicates() {

            // Create an array of objects
            subjects = [{
                title: "C++",
                author: "Rohit Gautam"
            }, {
                title: "JavaScript",
                author: "James"
            }, {
                title: "Python",
                author: "Ajit"
            }, {
                title: "ReactJS",
                author: "Sandeep"
            }, {
                title: "ReactJS",
                author: "Alok"
            }, {
                title: "ReactJS",
                author: "Ankit"
            }, ];

            // Display the list of array objects

            // Declare a new array
            let newArray = [];

            // Declare an empty object
            let otherObject = {};

            // Loop for the array elements
            for (let i in subjects) {

                // Extract the title
                objTitle = subjects[i]['title'];

                // Use the title as the index
                otherObject[objTitle] = subjects[i];

            // Loop to push unique object into array
            for (i in otherObject) {

            // Display the unique objects


Output :

How to remove duplicates from an array of objects using JavaScript?

How to remove duplicates from an array of objects using JavaScript?

Strategy 2:

Converting the exhibit to a Set to eliminate the copies: A Set item holds just extraordinary upsides of any sort. This property can be utilized to store just the items that are special in the cluster.

Each object of the cluster is first changed over into a JSON encoded string utilizing the JSON.stringify technique. The JSON encoded string is then planned to an exhibit utilizing the guide() strategy. Another set is made by passing this cluster to the new set constructor. This progression will eliminate every one of the copy components as the JSON encoded strings will be something similar for similar components.

The set is then changed over to an Array utilizing the from() strategy, passing the set as a boundary. This exhibit won’t have copied objects.


<!DOCTYPE html>

        How to remove duplicates from an array of objects using JavaScript ?

    <h1 style="color: red">
        Online Portfolio

        How to remove duplicates from an array of objects?

        Click on the button to remove the duplicated in the array

    <p>Check the console for the output</p>

    <button onclick="deleteDuplicates()">
        Remove Duplicate

    <script type="text/javascript">
        function deleteDuplicates() {

            // Create an array of objects
            subjects = [{
                title: "C++",
                author: "Rohit Gautam"
            }, {
                title: "JAVA",
                author: "Alok"
            }, {
                title: "Python",
                author: "Ajit"
            }, {
                title: "JAVA",
                author: "Alok"
            }, {
                title: "Python",
                author: "Ajit"
            }, {
                title: "C++",
                author: "Rohit Gautam"
            }, ];
            jsonObject =;


            uniqueSet = new Set(jsonObject);
            uniqueArray = Array.from(uniqueSet).map(JSON.parse);



remove duplicate

10 Amazing things you can build using JavaScript

10 Amazing things you can build using JavaScript

JavaScript Introduction :

JavaScript was established in 1995 by Brendan Eich. As of late, a study is led by StackOverflow and it is found in the overview that JavaScript is the most utilized and loved language on the earth (10 Amazing things you can build using JavaScript).

Additionally, A fascinating truth turned out in the study that back-end designers are destined to look in regards to JavaScript separated from some other language. Indeed, even java and .NET engineers likewise said that they need to learn something like an essential degree of JavaScript for their last activities.


Sites: JavaScript was established by Brendan Eich in 1995 to add intelligence and conduct to static sites and still now it is utilized for a similar reason. Each cutting-edge site has JavaScript somewhat. Wikipedia, Yahoo, and Amazon are a few sites that are assemble utilizing JavaScript.

Web applications: JavaScript has made it simple to make web applications. Take the case of Google maps wherein on the off chance that you need to look through an area on google maps you need to contact and drag the mouse and you see a segment of the guide which is less filled while the zoomed part is more filled. That is the means by which JavaScript works behind scenes. Gmail, Yahoo, and AOL are some web applications that are fabricated utilizing JavaScript.

Introductions: Nowadays JavaScript is additionally used to make introductions very much like sites. RevealJS library is utilized to make introductions in case you know about CSS and HTML. In the event that you don’t know HTML and CSS, you can Try utilizing which depends on the RevealJS library.

Smartwatch applications: Pebble, a smartwatch-production organization has made pebble.js, a JavaScript structure that permits clients or designers to make an application for watches in JavaScript. In any case, till now it isn’t accessible in IOS and Android watches.

Portable applications: Mobile applications can be made utilizing JavaScript. Prior it is by all accounts an alternate undertaking to make an application for mobiles as various applications are needed for android and IOS as various dialects are needed to make applications for them and more designers are needed. Yet, this assignment should handily be possible utilizing JavaScript and React Native where a solitary application can be utilized on both Android and IOS cell phones. Like Walmart, Airbnb, and Facebook are fabricate utilizing respond and JavaScript.

Program-based games: Browser-based gaming has purchased another blast in the internet gaming industry. Happening to the HTML5 has taken it to another level. It will be intriguing to perceive how this section will advance later on. CrossCode and Swoop are instances of program-based games.

Flying robots and robots: Basic robots are furnished with a working framework and thus, you can introduce NodeJS on it. So subsequent to introducing it you can without much of a stretch program the robots utilizing JavaScript. AR Drone 2.0 is a viable illustration of this that offers a very good quality API to transfer video, read information back, and get orders.

Worker application: With the happening to NodeJS a couple of years back, JavaScript makes its course from the program and in the worker. However long then, at that point, Node has been utilized by numerous enormous organizations for Example – Paypal, Linkedin, medium, and Uber as a significant piece of back-end framework.

Web workers: JavaScript has made it simple to make web servers like in only 10 lines of code, you can develop an essential web worker. However, you can make more practical workers by utilizing a hub or by utilizing a standard system like express. Hub hi world application and apache tomcat are a few instances of web workers.

Craftsmanship: The material component is another element added as of late in HTML5 which helps in delivering or adding three-dimensional items or shapes to the programs. This has made the program another wellspring of computerized workmanship. For instance, solid shapes, cuboids,s, and triangles can be made utilizing JavaScript.

These are some astonishing things you can do utilizing JavaScript and there are significantly more coming sooner rather than later

Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer

Web Designer Top Interview Question and Answer : After collecting questions from many interviews. I came to search for those answer which is needed for the interviews question. These questions are very interesting which covers mostly HTML, CSS/ JavaScript, and jQuery, and Experience a couple of years. This is going to be very useful before anyone faces any interview.


In CSS when will you use a CSS float?

Ans –  The “float” CSS property specifies that an element should be placed along the left or right side of its container, where text and inline elements will wrap around it.

Q2 – While writing an error message what are all things do you need to take into consideration?

Ans –  Be Clear And Not Ambiguous

Be Short And Meaningful

Be Humble

Be Specific And Relevant

Don’t Use Technical Jargons.

Avoid Negative Words

Avoid Uppercase Text.

Give Direction to User

Explain what a Grid System is?

Ans –  There is nothing worse for an artist than a blank canvas. A grid system is a set of measurements a graphic designer can use to align and size objects within the given format. Although there are a few different categories of grid systems, there are no strict rules on what can or cannot be a grid. It’s up to you. Any guides that help you shape the final design are okay.

Q4 – What does is NaN Function do?

Answer –  The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value equates to NaN. Otherwise, it returns false.

isNaN(123) //false

isNaN(-1.23) //false

isNaN(52) //false

isNaN(0) //false

isNaN(‘123’) //false

isNaN(‘Hello’) //true

isNaN(‘2005/12/12’) //true

isNaN() //false

isNaN(true) //false

isNaN(undefined) //true

isNaN(‘NaN’) //true

isNaN(NaN) //true

Explain What is Information Architecture?

Answer –  Information architecture (IA) is the structural design of shared information environments; the art and science of organizing and labelling websites, intranets, online communities and software to support usability and findability; and an emerging community of practice focused on bringing principles of design, architecture and information science to the digital landscape.

What is the difference between span & Div?

Answer –  The primary difference between a div and a span is their default behavior. By default, a <div> is a block-level-element and a <span> is an inline element. In other words, if you want to adjust a small portion of text and not break it out of the current line, you should use a <span>. If you need to modify a large division, the height, move an element, or contain other elements, you should use a <div>.

What is Mobile-First Design ?.

Answer – Responsive design starts on the desktop; that is, at the maximum required resolution, and then scales down to the smallest screen. Even though the content and layout contract to fit smartphones, the navigation, content, and download speeds are geared more for your traditional website.

Mobile-first design is similar to designing a mobile app and then adapting the layout that it can be viewed neatly on tablet and desktop devices without too many modifications. Your whole design and layout are based on providing an excellent mobile user experience: fast download speeds, rich media content to keep your target audience interested, easy touchscreen navigation, and so on.


Responsive design sounds good, we hear you say. Why should you risk a mobile-first design? Quite simply, the stats show that we have become addicted to surfing on mobile devices. Currently, 52.64% of the total traffic on the Internet is done via mobile phones, and by the end of the year experts from Zenith Media predict an increase of up to 75%. With this information in mind, it is essential to understand what mobile-first design is and what its benefits are. Unlike responsive design, mobile-first is about a complete mobile user experience: adapted app-like user interface, less text, larger fonts, fast download speed, video and audio, one call-to-action per page, short forms, etcetera. Additionally, mobile browsers shortly will have access to more of the smartphone features like camera, haptic feedback, voice detection, so that a mobile-first design will be able to provide a unique experience to put your site ahead of the competition and drive traffic.

Difference between bootstrap3 and bootstrap 4?

Answer – Bootstrap 3 Source CSS Files is LESS.

Bootstrap 4 Source CSS files Converted in SCSS. 

Bootstrap 3 has 4 grid system (col-xs-3, col-sm-3, col-md-3, col-lg-3).

Bootstrap 4 has 5 grid system (.col-, .col-sm-3, .col-md-3, .col-lg-3, .col-xl-3). Bootstrap 4 has removed the xs from the lowest break point. Therefore, (col-) covers all devices. 

Bootstrap 3 Offset class is like this (col-md-offset-4).

Bootstrap 4 has changed the offset class (offset-md-4). 

In Bootstrap 3 we are used this (.img-responsive) class for the responsive images.

Bootstrap 4 has changed the class for responsive image (.img-fluid). 

In Bootstrap 3 we are used (.input-lg) and (.input-sm) to increase and decrease the input size.

Bootstrap 4 has changed to (.form-control-lg) and (.form-control-sm) to increase and decrease the input size.

What is the difference between Body.Onload() & document.ready() ?

Answer- The main differences between the two are:

  1. Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery’s document.ready() event will be called once the DOM is loaded i.e., it won’t wait for the resources like images to get loaded. Hence, the functions in jQuery’s ready event will get executed once the HTML structure is loaded without waiting for the resources.
  2. We can have multiple document.ready() in a page but Body.Onload() event cannot.

What are the Different JavaScript Types?

Answer- In JavaScript, there are two different kinds of data: primitives, and objects. A primitive is simply a data type that is not an object and has no methods.

In JS, there are six primitive data types:


Boolean, Undefined,  Number, Null, String, Symbol

What about Objects?

Objects are not a primitive dataType.

An object is a collection of properties. These properties are stored in key/value pairs. Properties can reference any type of data, including objects and/or primitive values.

What is the prompt box?

Answer – The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page.

Note: When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.

The prompt() method returns the input value if the user clicks “OK”. If the user clicks “cancel” the method returns null.

What is the difference between HTML & HTML5?

Ans – The biggest advantage that HTML5 has over its unnumbered predecessor is that it has high-level audio and video support which was not a part of the version specifications in the previous HTML. Other differences between HTML and HTML5:

SVG, canvas and other virtual vector graphics are supported in HTML5, whereas in HTML, using vector graphics was only possible by using it in conjunction with different technologies like Flash, VML, and Silver-light, etc.

HTML5 uses web SQL databases, application cache for temporary storing data, meanwhile, in HTML, only browser cache could be utilized for this purpose.

Another difference between HTML and HTML5 worth mentioning is that the former doesn’t allow JavaScript to run within the web browser (it instead runs in the browser interface thread) whereas the latter provides full support for JavaScript to run in the background (This is a possible courtesy to the JS web worker API of HTML5).

HTML5 is not based on SGML, and that allows it to have improved parsing rules which provide enhanced compatibility.

In HTML5, inline MathML and SVG can be used in text whereas this wasn’t possible in HTML.

Some of the deprecated elements that have now been dropped completely are index, no frames, acronym, applet, basefont, dir, font, frame, frameset, big, center, strike, tt.

HTML5 supports new kinds of form controls, for example, dates and times, email, number, range, tel, url, search, etc.

There are many new elements introduced in HTML. Some of the most important ones are: summary, time, aside, audio, command, data, data list, details, embed, wbr, figcaption, figure, footer, header, article, hgroup, bdi, canvas, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, track, video.

What is $() in the jQuery library? 

Answer – The $() function is an alias of jQuery() function, at first it looks weird and makes jQuery code cryptic, but once you get used to it, you will love its brevity. $() function is used to wrap any object into a jQuery object, which then allows you to call various method-defined jQuery objects. You can even pass a selector string to the $()function, and it will return a jQuery object containing an array of all matched DOM elements. I have seen this jQuery asked several times, despite it’s quite basic, it is used to differentiate between developers who know jQuery or not.

 What is Grouping?

Answer – When more than one selector shares the same declaration, they may be grouped together via a comma-separated list; this allows you to reduce the size of the CSS (every bit and byte is important) and makes it more readable. The following snippet applies the same background to the first three heading elements.h1, h2, h3 {background: red;}

What is “Semantic Element”?

Ans – A semantic element clearly describes its meaning to both the browser and the developer.

Examples of non-semantic elements: <div> and <span> – Tells nothing about its content.

Examples of semantic elements: <form>, <table>, and <article> – Clearly defines its content.

Which command will give you a version of Jquery”?

Ans – The command $.ui.version returns jQuery UI version.

What is event bubbling?

Event bubbling is a term you might have come across on your JavaScript travels. It relates to the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example).

Why do we use metatag?

The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page but will be machine parsable.

Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.

The metadata can be used by browsers (how to display content or reload the page), search engines (keywords), or other web services.

What is a web worker?

Ans- When executing scripts on an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

What are webhooks?

Webhooks provide a mechanism whereby a server-side application can notify a client-side application when a new event (that the client-side application might be interested in) has occurred on the server. Webhooks operate on the concept of “event reaction” (don’t call me, I’ll call you if I have something new), and thus avoids the need for constant polling of the server-side application by the client-side application. Thus, rather than the client-side application constantly polling the server-side application to check for new events, the server-side application calls the client-side application (by invoking a client-provided webhook URL) anytime the server-side has something new to report to the client.

This is the core concept of the Webhook.

What is DOCTYPE!?

The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag.

The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.

In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language so that the browsers render the content correctly.

HTML5 is not based on SGML and therefore does not require a reference to a DTD.

Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.

What is the Callback Function? 

Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

Is JavaScript case sensitive?

Ans: Yes!

A function getElementById is not the same as getElementbyID.

 What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

What is the ‘this’ keyword in JavaScript?

‘This’ keyword refers to the object from where it was called.

What is closure in JavaScript?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Lexical scoping

Consider the following example code:

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

What is Hoisting in JavaScript?

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Days Counter Script

Days Counter Script

Days Counter Script

Days Counter Script : On the off chance that you’ve at any point considered the number of days are remaining from the date of launch, this content will reveal to you that. It very well may be adjusted to work with anytime, if not every one of them together!

We can show a days count script showing time left from an occasion. Let’s assume we are running a mission which will end following two days. Here we will show a counter saying days , hours , minutes and seconds left for the occasion to occur or the mission to end. This content uses the setTimeout work similarly as it is utilized in showing a changing clock script. Here this setTimeout script triggers another capacity in each 1000 factory seconds ( or in 1 sec ).

This content uses customer side JavaScript to produce the check down clock. The underlying worth in number of seconds left for the commencement to end will be passed to the capacity. At the hour of page stacking the seconds left ( a numeric worth ) is gathered and in light of this worth the days , hours, minutes and seconds are determined and shown.

Yon also check the days between two dates :

Days Calculator between two dates / JavaScript


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Days Counter</title>
    <div class="container">
        <div class="calendar">
            <div class="daysRemaining">
                Number of Days Remaining.
            <div class="result" id="demo">




.calendar {
            width: 99%;
            font-size: 50px;
            font-family: -webkit-pictograph;
            display: flex;
            justify-content: center;
            height: 90vh;
            align-items: center;
            border: 5px solid #b8ce9b;
            background-color: #d4efb1;
            flex-direction: column;
        .daysRemaining {
            font-size: 15px;


 // Set the date we're counting down to
 var countDownDate = new Date("Nov 24, 2021 09:00:00").getTime();
 // Update the count down every 1 second
 var x = setInterval(function() {
     // Get todays date and time
     var now = new Date().getTime();
     // Find the distance between now an the count down date
     var distance = countDownDate - now;

     // Time calculations for days, hours, minutes and seconds
     var days = Math.floor(distance / (1000 * 60 * 60 * 24));
     var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
     var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
     var seconds = Math.floor((distance % (1000 * 60)) / 1000);

     // Display the result in the element with id="demo"
     document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
         minutes + "m " + seconds + "s ";

     // If the count down is finished, write some text 
     if (distance < 0) {
         document.getElementById("demo").innerHTML = "EXPIRED";
 }, 1000);

Like us on Facebook – Online Portfolio

Seat Reservation with JavaScript

Seat Reservation with JavaScript

Seat Reservation with JavaScript : In this article I will show, How to implement seat booking with Pure JavaScript. Thus, I chose to compose on it. This post discloses how to execute seat booking with JavaScript . It tends to be utilized in online Bus, flight, inn, test backing, film and ticket booking framework.

A confounding variable about train travel in an unfamiliar nation is realizing what is important and what isn’t. This is particularly the situation with seat bookings for trains. For certain tickets you need to have a booking and with others it’s basically unrealistic. Thus we need to clear these things up for you, so you can travel like a neighborhood.

To put it plainly, a seating reservation implies you get a seat which is alloted to you by and by. Actually like a seat on an aircraft. Pulling up a chair reservation can be awesome thing yet not generally fundamental or conceivable. How might you know whether you need a booking or then again in case it is even conceivable to have one? First and foremost you need to figure out what sort of train you will be on.



<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Practice</title>
    <div class="bus">
        <div id="selectedseataDisplay">
        <div class="inner">
            <div class="leftside">
                <div id="s1" class="seat1"></div>
                <div id="s2" class="seat2"></div>
                <div id="s3" class="seat3"></div>
                <div id="s4" class="seat4"></div>
                <div id="s5" class="seat5"></div>
                <div id="s6" class="seat6"></div>
                <div id="s7" class="seat7"></div>
                <div id="s8" class="seat8"></div>
                <div id="s9" class="seat9"></div>
                <div id="s10" class="seat10"></div>
            <div class="rightside">
                <div id="s11" class="seat11"></div>
                <div id="s12" class="seat12"></div>
                <div id="s13" class="seat13"></div>
                <div id="s14" class="seat14"></div>
                <div id="s15" class="seat15"></div>
                <div id="s16" class="seat16"></div>
                <div id="s17" class="seat17"></div>
                <div id="s18" class="seat18"></div>
                <div id="s19" class="seat19"></div>
                <div id="s20" class="seat20"></div>



 .bus {
        display: flex;
        justify-content: center;

    .inner {
        display: flex;
        justify-content: space-between;
        width: 700px;

    .rightside {
        margin-left: 20px;

    .rightside {
        display: flex;
        flex-wrap: wrap;

    .leftside div,
    .rightside div {
        width: 100px;
        height: 100px;
        background-color: rebeccapurple;
        border-top-left-radius: 30px;
        border-top-right-radius: 30px;
        margin-top: 15px;
        margin-left: 10px;
        cursor: pointer;
        border: 5px solid #d4a8ff;

    .leftside div:hover,
    .rightside div:hover {
        background-color: #d4a8ff;
        border: 5px solid rebeccapurple;

    .selected:hover {
        background-color: #7ace7d !important;
        border: 5px solid #37a262 !important;
        display: flex;
    flex-wrap: wrap;
    width: 200px;
    height: 200px;
    margin-top: 20px;
    #selectedseataDisplay li{
    background-color: #7ace7d;
    color: #fff;
    text-transform: capitalize;
    font-size: 14px;
    font-weight: bold;
    font-family: monospace;
    padding: 5px;
    list-style: none;
    height: 35px;
    width: 60px;
    margin-right: 5px;
    border: 2px solid #37a262;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    text-align: center;


 const selectedSeat = [];
    document.addEventListener('click', function (e) {
        e = e || window.event;
        const target = || e.srcElement,
            text = target.className;
        let seatNumber = text;
        textID =;
        if (document.getElementById(textID).classList.contains("selected")) {
        else {
            let seatTo = text.split(" ");
            let seatToRemove = seatTo[0];
            for (let i = 0; i < selectedSeat.length; i++) {
                if (selectedSeat[i] === seatToRemove) {
                    selectedSeat.splice(i, 1);
        console.log('selectedSeat are ', selectedSeat);
        document.getElementById('selectedseataDisplay').innerHTML = '';
        for(let j=0; j<selectedSeat.length;j++){
                        document.getElementById('selectedseataDisplay').innerHTML += "<li>"+selectedSeat[j]+"</li>";

    }, false);

Live Demo

See the Pen Seat Reservation with JavaScript by Rohit Gautam (@TheRrohitt) on CodePen.

Setup React App

Create React App

Setup React App

Setup React App

Setup React App : is an agreeable climate for learning React and is the most ideal approach to begin assembling another single-page application in React.

ReactJS is a declarativeefficient, and flexible JavaScript library for building reusable UI components. It is an open-source, component-based front end library which is responsible only for the view layer of the application. It was initially developed and maintained by Facebook and later used in its products like WhatsApp & Instagram.

Respond makes it effortless to make intuitive UIs. Plan straightforward perspectives for each state in your application, and React will effectively refresh and deliver the perfect segments when your information changes.

Explanatory perspectives make your code more unsurprising and simpler to investigate


It sets up your advancement climate with the goal that you can utilize the most recent JavaScript highlights, gives a pleasant designer experience, and enhances your application for creation. You’ll have to have Node >= 10.16 and npm >= 5.6 on your machine. To make an undertaking, run:



npm create-react-app my-application
cd my-application
npm start


Make React App doesn’t deal with backend rationale or data sets; it simply makes a frontend construct pipeline, so you can utilize it with any backend you need. In the engine, it utilizes Babel and webpack, however you don’t have to know anything about them.

You can study Create React App from its README and the User Guide.