javascript_interview_questions

JavaScript Interview Questions and Answers

Click if you like the project. Pull Request are highly appreciated.

Table of Contents

Q. What is difference between document.getElementById() and document.querySelector()?

document.getElementById(): Returns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

element = document.getElementById(id);

document.querySelector(): Returns the first matching Element node within the node’s subtree. If no matching node is found, null is returned.

element = document.querySelector(selectors);

document.querySelectorAll(): Returns a NodeList containing all matching Element nodes within the node’s subtree, or an empty NodeList if no matches are found.

element = document.querySelectorAll(selectors);

Note: querySelector() is more useful when we want to use more complex selectors.

↥ back to top

Q. When to use reduce(), map(), foreach() and filter() in JavaScript?

forEach(): It takes a callback function and run that callback function on each element of array one by one.

Basically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them.

var arr = [10, 20, 30];

arr.forEach(function (elem, index){
   console.log(elem + ' comes at ' + index);
})

Output

10 comes at 0
20 comes at 1
30 comes at 2

filter(): The main difference between forEach() and filter() is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array.

Note: filter does not update the existing array it will return a new filtered array every time.

var arr = [10, 20, 30]; 

var result = arr.filter(function(elem){
    return elem !== 20;
})
console.log(result)

Output

[10, 30]

map(): map() like filter() & forEach() takes a callback and run it against every element on the array but whats makes it unique is it generate a new array based on your existing array.

Like filter(), map() also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array.

var arr = [10, 20, 30];

var mapped = arr.map(function(elem) {
    return elem * 10;
});
console.log(mapped)

Output

[100, 200, 300]

reduce(): reduce() method of the array object is used to reduce the array to one single value.

var arr = [10, 20, 30];

var sum = arr.reduce(function(sum, elem) {
    return sum + elem;
});
console.log(sum); // Output: 60
↥ back to top

Q. What is Hoisting in JavaScript?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Example 01: Variable Hoisting

console.log(message); // output : undefined
var message = "The variable Has been hoisted";

The above code looks like as below to the interpreter,

var message;
console.log(message);
message = "The variable Has been hoisted";

Example 02: function Hoisting

function hoist() {
  a = 20;
  var b = 100;
}

hoist();

console.log(a); 
/* 
Accessible as a global variable outside hoist() function
Output: 20
*/

console.log(b); 
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/

All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

console.log(a);
let a = 3;

// Output: ReferenceError: a is not defined

They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call Temporal Dead Zone, A time span between variable creation and its initialization where they can’t be accessed.

Note: JavaScript only hoists declarations, not initialisation

↥ back to top

Q. What are closures?

A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains

function Welcome(name) {
  var greetingInfo = function(message) {
    console.log(message+' '+name);
  }
  return greetingInfo;
}
var myFunction = Welcome('John');
myFunction('Welcome '); // Output: Welcome John
myFunction('Hello Mr.'); // output: Hello Mr.John

As per the above code, the inner function greetingInfo() has access to the variables in the outer function Welcome() even after outer function has returned.

↥ back to top

Q. How do you clone an object in JavaScript?

Using the object spread operator …, the object’s own enumerable properties can be copied into the new object. This creates a shallow clone of the object.

const obj = { a: 1, b: 2 }
const shallowClone = { ...obj }

With this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.

Other alternatives include:

↥ back to top

Q. What are the possible ways to create objects in JavaScript?

Object constructor: The simpliest way to create an empty object is using Object constructor. Currently this approach is not recommended.

 var object = new Object();

Object’s create method: The create method of Object creates a new object by passing the prototype object as a parameter

 var object = Object.create(null);

Object literal syntax: The object literal syntax is equivalent to create method when it passes null as parameter

 var object = {};

Function constructor: Create any function and apply the new operator to create object instances,

 function Person(name) {
  var object = {};
  object.name = name;
  object.age = 26;
  return object;
 }
 var object = new Person("Alex");

Function constructor with prototype: This is similar to function constructor but it uses prototype for their properties and methods,

function Person(){}
Person.prototype.name = "Alex";
var object = new Person();

This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.

function func {};

new func(x, y, z);

// **(OR)**

// Create a new instance using function prototype.
var newInstance = Object.create(func.prototype)

// Call the function
var result = func.call(newInstance, x, y, z),

// If the result is a non-null object then use it otherwise just use the new instance.
console.log(result && typeof result === 'object' ? result : newInstance);

ES6 Class syntax: ES6 introduces class feature to create the objects

class Person {
 constructor(name) {
    this.name = name;
 }
}

var object = new Person("Alex");

Singleton pattern: A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don’t accidentally create multiple instances.

var object = new function() {
  this.name = "Alex";
}
↥ back to top

Q. What are the javascript data types?

Below are the list of javascript data types available

  1. Number
  2. String
  3. Boolean
  4. Object
  5. Undefined

Q. What are global variables?

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

msg = "Hello" // var is missing, it becomes global variable

The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.

Q. What is variable shadowing in javascript?

Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.

If there’s a variable in the global scope, and you’d like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope.

var val = 10;

function Hoist(val) {
    alert(val);
}

Hoist(20);

Output

20
↥ back to top

Q. What is an event flow?

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object.

There are two ways of event flow

Q. What is event bubbling?

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

Example: If you click on EM, the handler on DIV runs.

<div onclick="alert('The handler!')">
  <em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
</div>

Stopping bubbling

<body onclick="alert(`the bubbling doesn't reach here`)">
  <button onclick="event.stopPropagation()">Click me</button>
</body>

Q. What is event capturing?

Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.

Q. What is prototype chain?

Nearly all objects in JavaScript are instances of Object. That means all the objects in JavaScript inherit the properties and methods from Object.prototype. This is called Prototype chaining.

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructors function is available through Object.prototype.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}
//Person class created
Person.prototype.getFullName = function() {
  return this.firstName + " " + this.lastName;
}

// we have added getFullName method in Person’s prototype.
var person = new Person("John", "K", 25);
// It will create an instance of the Person class
> person.hasOwnProperty("firstName");  // true
> person.hasOwnProperty("getFullName");  // false
> person.getFullName(); // John K

Q. What is the difference between Call, Apply and Bind?

call(): The call() method invokes a function with a given this value and arguments provided one by one

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.call(employee1, 'Hello', 'How are you?'); // Hello John Rodson, How are you?
invite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

apply(): Invokes the function and allows you to pass in arguments as an array

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.apply(employee1, ['Hello', 'How are you?']); // Hello John Rodson, How are you?
invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?

bind(): returns a new function, allowing you to pass in an array and any number of arguments

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1('Hello', 'How are you?'); // Hello John Rodson, How are you?
inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?
↥ back to top

Q. What is the difference between == and === operators?

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,

  1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  2. Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this,
    1. NaN is not equal to anything, including NaN.
    2. Positive and negative zeros are equal to one another.
  3. Two Boolean operands are strictly equal if both are true or both are false.
  4. Two objects are strictly equal if they refer to the same Object.
  5. Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined –> false but null==undefined –> true

Some of the example which covers the above cases

0 == false   // true
0 === false  // false
1 == "1"     // true
1 === "1"    // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
↥ back to top

Q. What is a first class function?

JavaScript functions are first-class functions meaning functions and objects are treated as the same thing. Functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function “first-class citizens in JavaScript”

Example: Assign a function to a variable

const message = function() {
   console.log("Hello World!");
}

message(); // Invoke it using the variable

Example: Pass a function as an Argument

function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");

Example: Return a function

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}

Example: Using a variable

const sayHello = function() {
   return function() {
      console.log("Hello!");
   }
}
const myFunc = sayHello();
myFunc();

Example: Using double parentheses

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
sayHello()();

We are using double parentheses ()() to invoke the returned function as well.

Q. What is a higher order function?

A Higher-Order function is a function that receives a function as an argument or returns the function as output.

For example, Array.prototype.map(), Array.prototype.filter() and Array.prototype.reduce() are some of the Higher-Order functions in javascript.

const arr1 = [1, 2, 3];
const arr2 = arr1.map(function(item) {
  return item * 2;
});
console.log(arr2);

Q. What is a unary function?

Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.

const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value

Q. What is currying function?

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.

function volume(length) {
  return function(width) {
    return function(height) {
      return height * width * length;
    }
  }
}

volume(2)(3)(4); // 24

Curried functions are great to improve code re-usability and functional composition.

Q. What is a pure function?

Pure functions are functions that accept an input and returns a value without modifying any data outside its scope(Side Effects). Its output or return value must depend on the input/arguments and pure functions must return a value.

Example

function impure(arg) {
    finalR.s = 90
    return arg * finalR.s
}

The above function is not a pure function because it modified a state finalR.s outside its scope.

function pure(arg) {
    return arg * 4
}

Here is a pure function. It didn’t side effect any external state and it returns an output based on the input.

A function must pass two tests to be considered “pure”:

  1. Same inputs always return same outputs
  2. No side-effects

1. Same Input => Same Output
Compare this:

const add = (x, y) => x + y;

add(2, 4); // 6

To this

let x = 2;

const add = (y) => {
  x += y;
};

add(4); // x === 6 (the first time)

2. Pure Functions = Consistent Results
The first example returns a value based on the given parameters, regardless of where/when you call it.

If you pass 2 and 4, you’ll always get 6.

Nothing else affects the output.

Benefits

↥ back to top

Q. What is memoization in JavaScript?

Memoization is a programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache.

// A simple memoized function to Add Number
const memoizedAdd = () => {
  let cache = {};
  return (number) => {
    if (number in cache) {
      console.log('Fetching from cache: ');
      return cache[number];
    }
    else {
      console.log('Calculating result: ');
      let result = number + 10;
      cache[number] = result;
      return result;
    }
  }
}
// returned function from memoizedAdd
const sum = memoizedAdd();
console.log(sum(10)); // Calculating result: 20
console.log(sum(10)); // Fetching from cache: 20
↥ back to top

Q. What is a service worker?

A Service worker is basically a JavaScript file that runs in background, separate from a web page and provide features that don’t need a web page or user interaction.

Some of the major features of service workers are

Lifecycle of a Service Worker
It consists of the following phases:

Registering a Service Worker
To register a service worker we first check if the browser supports it and then register it.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/ServiceWorker.js')
  .then(function(response) {
    
    // Service worker registration done
    console.log('Registration Successful', response);
  }, function(error) {
    // Service worker registration failed
    console.log('Registration Failed', error);
  }

Installation of service worker
After the controlled page that takes care of the registration process, we come to the service worker script that handles the installation part.

Basically, you will need to define a callback for the install event and then decide on the files that you wish to cache. Inside a callback, one needs to take of the following three points –

Example: service-worker.html

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Service Worker</title>
</head>
<body>
(Look in the console.)
<script>
(function() {
    "use strict";

    if (!navigator.serviceWorker || !navigator.serviceWorker.register) {
        console.log("This browser doesn't support service workers");
        return;
    }

    // Listen to messages from service workers.
    navigator.serviceWorker.addEventListener('message', function(event) {
        console.log("Got reply from service worker: " + event.data);
    });

    // Are we being controlled?
    if (navigator.serviceWorker.controller) {
        // Yes, send our controller a message.
        console.log("Sending 'hi' to controller");
        navigator.serviceWorker.controller.postMessage("hi");
    } else {
        // No, register a service worker to control pages like us.
        // Note that it won't control this instance of this page, it only takes effect
        // for pages in its scope loaded *after* it's installed.
        navigator.serviceWorker.register("service-worker.js")
            .then(function(registration) {
                console.log("Service worker registered, scope: " + registration.scope);
                console.log("Refresh the page to talk to it.");
                // If we want to, we might do `location.reload();` so that we'd be controlled by it
            })
            .catch(function(error) {
                console.log("Service worker registration failed: " + error.message);
            });
    }
})();
</script>
</body>
</html>

service-worker.js

self.addEventListener("message", function(event) {
    //event.source.postMessage("Responding to " + event.data);
    self.clients.matchAll().then(all => all.forEach(client => {
        client.postMessage("Responding to " + event.data);
    }));
});

Q. How do you reuse information across service worker restarts?

The problem with service worker is that it get terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.

Q. What is a post message?

Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).

Q. What is a web-storage event and its event handler?

The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below

  window.onstorage = functionRef;

Let’s take the example usage of onstorage event handler which logs the storage key and it’s values

if (typeof(Storage) !== "undefined") {
  window.onstorage = function(e) {
    console.log('The ' + e.key +
      ' key has been changed from ' + e.oldValue +
      ' to ' + e.newValue + '.');
  };
} else {
  // Browser doesnot support web-storage 
}
↥ back to top

Q. How to use Web Workers in javascript?

Step 01: Create a Web Workers file: Write a script to increment the count value.

// counter.js
let i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}

timedCount();

Here postMessage() method is used to post a message back to the HTML page.

Step 02: Create a Web Worker Object: Create a web worker object by checking for browser support.

if (typeof(w) == "undefined") {
  w = new Worker("counter.js");
}

and we can receive messages from web workers

w.onmessage = function(event){
  document.getElementById("message").innerHTML = event.data;
};

Step 03: Terminate a Web Workers: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use terminate() method to terminate listening the messages.

w.terminate();

Step 04: Reuse the Web Workers: If you set the worker variable to undefined you can reuse the code

w = undefined;

Example:

<!DOCTYPE html>
<html>
<body>
  <p>Count numbers: <output id="result"></output></p>
  <button onclick="startWorker()">Start</button>
  <button onclick="stopWorker()">Stop</button>
  
  <script>
    var w;
    
    function startWorker() {
      if (typeof(Worker) !== "undefined") {
        if (typeof(w) == "undefined") {
          w = new Worker("counter.js");
        }
        w.onmessage = function(event) {
          document.getElementById("result").innerHTML = event.data;
        };
      } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
      }
    }
    
    function stopWorker() {
      w.terminate();
      w = undefined;
    }
  </script>
</body>
</html>
↥ back to top

Q. What are the restrictions of web workers on DOM?

WebWorkers don’t have access to below javascript objects since they are defined in an external files

  1. Window object
  2. Document object
  3. Parent object

Q. What is a promise?

A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending. Syntax

const promise = new Promise(function(resolve, reject) {
  // promise description
})

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

Promises have three states:

  1. Pending: This is an initial state of the Promise before an operation begins
  2. Fulfilled: This state indicates that specified operation was completed.
  3. Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.

Q. What is a callback function?

A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action.

function callbackFunction(name) {
  console.log('Hello ' + name);
}

function outerFunction(callback) {
  let name = prompt('Please enter your name.');
  callback(name);
}

outerFunction(callbackFunction);

Q. Why do we need callbacks?

The callbacks are needed because javascript is a event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events. Let’s take an example with first function invoking an API call(simulated by setTimeout) and next function which logs the message.

function firstFunction() {
  // Simulate a code delay
  setTimeout( function() {
    console.log('First function called');
  }, 1000 );
}
function secondFunction() {
  console.log('Second function called');
}
firstFunction();
secondFunction();

Output
// Second function called
// First function called

As observed from the output, javascript didn’t wait for the response of first function and remaining code block get executed. So callbacks used in a way to make sure that certain code doesn’t execute until other code finished execution.

Q. What is a callback hell?

Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,

async1(function() {
    async2(function() {
        async3(function() {
            async4(function() {
                ....
            });
        });
    });
});
↥ back to top

Q. What is server-sent events?

Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This is been used in Facebook/Twitter updates, stock price updates, news feeds etc.

The EventSource object is used to receive server-sent event notifications. For example, we can receive messages from server as below,

if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("sse_generator.js");
  source.onmessage = function(event) {
    document.getElementById("output").innerHTML += event.data + "<br>";
  };
}

Below are the list of events available for server sent events

Event Description
onopen It is used when a connection to the server is opened
onmessage This event is used when a message is received
onerror It happens when an error occurs
↥ back to top

Q. What is callback in callback?

You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.

loadScript('/script1.js', function(script) {
    console.log('first script is loaded');

  loadScript('/script2.js', function(script) {

    console.log('second script is loaded');

    loadScript('/script3.js', function(script) {

        console.log('third script is loaded');
      // after all scripts are loaded
    });
  })
});

Q. What is promise chaining?

The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000);

}).then(function(result) {

  console.log(result); // 1
  return result * 2;

}).then(function(result) {

  console.log(result); // 2
  return result * 3;

}).then(function(result) {

  console.log(result); // 6
  return result * 4;

});

In the above handlers, the result is passed to the chain of .then() handlers with the below work flow,

  1. The initial promise resolves in 1 second,
  2. After that .then handler is called by logging the result(1) and then return a promise with the value of result * 2.
  3. After that the value passed to the next .then handler by logging the result(2) and return a promise with result * 3.
  4. Finally the value passed to the last .then handler by logging the result(6) and return a promise with result * 4.
↥ back to top

Q. What is promise.all()?

Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected.

Promise.all([Promise1, Promise2, Promise3]) 
        .then(result) => {   
            console.log(result) 
          }) 
        .catch(error => console.log(`Error in promises ${error}`));

Note: Remember that the order of the promises(output the result) is maintained as per input order.

Q. What is the purpose of race method in promise?

Promise.race() method will return the promise instance which is firstly resolved or rejected. Let’s take an example of race() method where promise2 is resolved first

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
});
var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value); // "two" // Both promises will resolve, but promise2 is faster
});

Q. What is a strict mode in javascript?

Strict Mode is a new feature in ECMAScript 5 that allows to place a program, or a function, in a strict operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression 'use strict'; instructs the browser to use the javascript code in the Strict mode.

Strict mode is useful to write secure javaScript by notifying “bad syntax” into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

The strict mode is declared by adding “use strict”; to the beginning of a script or a function. If declare at the beginning of a script, it has global scope.

'use strict';
x = 3.14; // This will cause an error because x is not declared

and if you declare inside a function, it has local scope

x = 3.14;       // This will not cause an error.
myFunction();

function myFunction() {
  'use strict';
  y = 3.14;   // This will cause an error
}
↥ back to top

Q. What is the purpose of double exclamation?

The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true. For example, you can test IE version using this expression as below,

let isIE11 = false;
isIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
console.log(isIE11); // returns true or false

If you don’t use this expression then it returns the original value.

console.log(navigator.userAgent.match(/Trident.*rv[ :]*11\./));  // returns either an Array or null

Note: The expression !! is not an operator, but it is just twice of ! operator.

Q. What is the purpose of delete operator?

The delete keyword is used to delete the property as well as its value.

var user= {name: "John", age:20};
delete user.age;

console.log(user); // {name: "John"}

Q. What is typeof operator?

You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.

typeof "John Abraham"     // Returns "string"
typeof (1 + 2)        // Returns "number"

Q. What is undefined property?

The undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too.

var user;    // Value is undefined, type is undefined
console.log(typeof(user)) //undefined

Any variable can be emptied by setting the value to undefined.

user = undefined
↥ back to top

Q. What is the difference between null and undefined?

Below are the main differences between null and undefined,

Null Undefined
It is an assignment value which indicates that variable points to no object. It is not an assignment value where a variable has been declared but has not yet been assigned a value.
Type of null is object Type of undefined is undefined
The null value is a primitive value that represents the null, empty, or non-existent reference. The undefined value is a primitive value used when a variable has not been assigned a value.
Indicates the absence of a value for a variable Indicates absence of variable itself
Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations

Q. What is eval?

The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.

console.log(eval('1 + 2')); //  3

Q. What is the difference between window and document?

The window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

The document object is html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc.

Window Document
It is the root level element in any web page It is the direct child of the window object. This is also known as Document Object Model(DOM)
By default window object is available implicitly in the page You can access it via window.document or document.
It has methods like alert(), confirm() and properties like document, location It provides methods like getElementById(), getElementByTagName(), createElement() etc

Q. How do you access history in javascript?

The window.history object contains the browsers history. You can load previous and next URLs in the history using back() and next() methods.

function goBack() {
  window.history.back()
}
function goForward() {
  window.history.forward()
}

Note: You can also access history without window prefix.

↥ back to top

Q. What is isNaN?

The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.

isNaN('Hello') //true
isNaN('100') //false
typeof(NaN) //Number

Q. What are the differences between undeclared and undefined variables?

Below are the major differences between undeclared and undefined variables,

undeclared undefined
These variables do not exist in a program and are not declared These variables declared in the program but have not assigned any value
If you try to read the value of an undeclared variable, then a runtime error is encountered If you try to read the value of an undefined variable, an undefined value is returned.

Q. What is NaN property?

The NaN property is a global property that represents “Not-a-Number” value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases

Math.sqrt(-1)
parseInt("Hello")
↥ back to top

Q. What is the purpose of isFinite function?

The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(100);         // true

Q. How do you submit a form using JavaScript?

You can submit a form using JavaScript use document.form[0].submit(). All the form input’s information is submitted using onsubmit event handler

function submit() {
    document.form[0].submit();
}
↥ back to top

Q. How do you find operating system details?

The window.navigator object contains information about the visitor’s browser os details. Some of the OS properties are avaialble under platform property,

console.log(navigator.platform);

Q. What is the difference between document load and DOMContentLoaded events?

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).

Q. What is the difference between native, host and user objects?

Q. What are the pros and cons of promises over callbacks?

Below are the list of pros and cons of promises over callbacks,
Pros:

  1. It avoids callback hell which is unreadable
  2. Easy to write sequential asynchronous code with .then()
  3. Easy to write parallel asynchronous code with Promise.all()
  4. Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)

Cons:

  1. It makes little complex code
  2. You need to load a polyfill if ES6 is not supported
↥ back to top

Q. What is the difference between an attribute and a property?

Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value,

<input type="text" value="Name:">

You can retrieve the attribute value as below,

const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Good morning
console.log(input.value); // Good morning

And after you change the value of the text field to “Good evening”, it becomes like

console.log(input.getAttribute('value')); // Good morning
console.log(input.value); // Good evening

Q. What is same-origin policy?

The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).

Q. What is the purpose of void(0)?

The void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML document that uses href="JavaScript:void(0);" within an <a> element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression.
For example, the below link notify the message without reloading the page

<a href="JavaScript:void(0);" onclick="alert('Well done!')">Click Me!</a>

Q. Is JavaScript a compiled or interpreted language?

JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

Q. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language. The language keywords, variables, function & object names, and any other identifiers must always be typed with a consistent capitalization of letters.

Q. What are events?

Events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react on these events. Some of the examples of HTML events are,

  1. Web page has finished loading
  2. Input field was changed
  3. Button was clicked

Let’s describe the behavior of click event for button element,

<!doctype html>
<html>
<head>
  <script>
    function greeting() {
      alert('Hello! Good morning');
    }
  </script>
</head>
<body>
  <button type="button" onclick="greeting()">Click me</button>
</body>
</html>
↥ back to top

Q. What is the use of preventDefault method?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyper link are some common usecases.

document.getElementById("link").addEventListener("click", function(event) {
   event.preventDefault();
});

Note: Remember that not all events are cancelable.

Q. What is the use of stopPropagation method?

The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)

<p>Click DIV1 Element</p>
<div onclick="secondFunc()">DIV 2
  <div onclick="firstFunc(event)">DIV 1</div>
</div>

<script>
function firstFunc(event) {
  alert("DIV 1");
  event.stopPropagation();
}

function secondFunc() {
  alert("DIV 2");
}
</script>

Q. What are the steps involved in return false usage?

The return false statement in event handlers performs the below steps,

  1. First it stops the browser’s default action or behaviour.
  2. It prevents the event from propagating the DOM
  3. Stops callback execution and returns immediately when called.

Q. What is BOM?

The Browser Object Model (BOM) allows JavaScript to “talk to” the browser. It consists of the objects navigator, history, screen, location and document which are children of window. The Browser Object Model is not standardized and can change based on different browsers.

↥ back to top

Q. What is the use of setTimeout?

The setTimeout() method is used to call a function or evaluates an expression after a specified number of milliseconds. For example, let’s log a message after 2 seconds using setTimeout method,

setTimeout(function() { console.log("Good morning"); }, 2000);

Q. What is the use of setInterval?

The setInterval() method is used to call a function or evaluates an expression at specified intervals (in milliseconds). For example, let’s log a message after 2 seconds using setInterval method,

setInterval(function() { console.log("Good morning"); }, 2000);

Q. Why is JavaScript treated as Single threaded?

JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.

Q. What is an event delegation?

Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it. For example, if you wanted to detect field changes in inside a specific form, you can use event delegation technique,

var form = document.querySelector('#registration-form');

// Listen for changes to fields inside the form
form.addEventListener('input', function (event) {

// Log the field that was changed
console.log(event.target);

}, false);
↥ back to top

Q. What is ECMAScript?

ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.

Q. What is JSON?

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built in JavaScript.

Q. What are the syntax rules of JSON?

Below are the list of syntax rules of JSON

  1. The data is in name/value pairs
  2. The data is separated by commas
  3. Curly braces hold objects
  4. Square brackets hold arrays

Q. What is the purpose JSON stringify?

When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.

var userJSON = {'name': 'John', age: 31}
var userString = JSON.stringify(user);
console.log(userString); //"{"name":"John","age":31}"

Q. How do you parse JSON string?

When receiving the data from a web server, the data is always in a string format. But you can convert this string value to javascript object using parse() method.

var userString = '{"name":"John","age":31}';
var userJSON = JSON.parse(userString);
console.log(userJSON);// {name: "John", age: 31}
↥ back to top

Q. What is the purpose of clearTimeout method?

The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout() function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer. For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.

var msg;
function greeting() {
  alert('Good morning');
}
function start() {
  msg =setTimeout(greeting, 3000);
}
function stop() {
    clearTimeout(msg);
}

Q. What is the purpose of clearInterval method?

The clearInterval() function is used in javascript to clear the interval which has been set by setInterval() function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval. For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by clearInterval() method.

var msg;
function greeting() {
  alert('Good morning');
}
function start() {
  msg = setInterval(greeting, 3000);
}
function stop() {
    clearInterval(msg);
}
↥ back to top

Q. How do you redirect new page in javascript?

In vanilla javascript, you can redirect to a new page using location property of window object. The syntax would be as follows,

function redirect() {
  window.location.href = 'newPage.html';
}

Q. How do you check whether a string contains a substring?

There are 3 possible ways to check whether a string contains a substring or not,

  1. Using includes: ES6 provided String.prototype.includes method to test a string contains a substring
    var mainString = "hello", subString = "hell";
    mainString.includes(subString)
    
  2. Using indexOf: In an ES5 or older environments, you can use String.prototype.indexOf which returns the index of a substring. If the index value is not equal to -1 then it means the substring exist in the main string.
    var mainString = "hello", subString = "hell";
    mainString.indexOf(subString) !== -1
    
  3. Using RegEx: The advanced solution is using Regular expression’s test method(RegExp.test), which allows for testing for against regular expressions
    var mainString = "hello", regex = "/hell/";
    regex.test(mainString)
    
↥ back to top

Q. How do you validate an email in javascript?

You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead client side. Because the javascript can be disabled on the client side.

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

The above regular expression regular accepts unicode characters.

Q. How do you get the current url with javascript?

You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purpose but this solution has issues in FF.

console.log('location.href', window.location.href); // Returns full URL

Q. What are the various url properties of location object?

The below Location object properties can be used to access URL components of the page

Properties Description
href The entire URL
protocol The protocol of the URL
host The hostname and port of the URL
hostname The hostname of the URL
port The port number in the URL
pathname The path name of the URL
search The query portion of the URL
hash The anchor portion of the URL

Q. How do get query string values in javascript?

You can use URLSearchParams to get query string values in javascript. Let’s see an example to get the client code value from URL query string,

const urlParams = new URLSearchParams(window.location.search);
const clientCode = urlParams.get('clientCode');

Q. How do you check if a key exists in an object?

You can check whether a key exists in an object or not using two approaches,

  1. Using in operator: You can use the in operator whether a key exists in an object or not
    "key" in obj
    

    and If you want to check if a key doesn’t exist, remember to use parenthesis,

    !("key" in obj)
    
  2. Using hasOwnProperty method: You can use hasOwnProperty to particularly test for properties of the object instance (and not inherited properties)
    obj.hasOwnProperty("key") // true
    
↥ back to top

Q. How do you loop through or enumerate javascript object?

You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn’t come from the prototype using hasOwnProperty method.

var object = {
    "k1": "value1",
    "k2": "value2",
    "k3": "value3"
};

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(key + " -> " + object[key]); // k1 -> value1 ...
    }
}

Q. How do you test for an empty object?

Using Object keys(ECMA 5+): You can use object keys length along with constructor type.

Object.keys(obj).length === 0 && obj.constructor === Object 

Using Object entries(ECMA 7+): You can use object entries length along with constructor type.

Object.entries(obj).length === 0 && obj.constructor === Object 
↥ back to top

Q. What is an arguments object?

The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let’s see how to use arguments object inside sum function,

function sum() {
    var total = 0;
    for (var i = 0, len = arguments.length; i < len; ++i) {
        total += arguments[i];
    }
    return total;
}

sum(1, 2, 3) // returns 6

Q. How do you make first letter of the string in an uppercase?

You can create a function which uses chain of string methods such as charAt, toUpperCase and slice methods to generate a string with first letter in uppercase.

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

Q. What are the pros and cons of for loop?

The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons

Pros

  1. Works on every environment
  2. You can use break and continue flow control statements

Cons

  1. Too verbose
  2. Imperative
  3. You might face one-by-off errors
↥ back to top

Q. How do you display the current date in javascript?

You can use new Date() to generate a new Date object containing the current date and time. For example, let’s display the current date in mm/dd/yyyy

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

Q. How do you compare two date objects?

You need to use use date.getTime() method to compare date values instead comparision operators (==, !=, ===, and !== operators)

var d1 = new Date();
var d2 = new Date(d1);
console.log(d1.getTime() === d2.getTime()); //True
console.log(d1 === d2); // False

Q. How do you check if a string starts with another string?

You can use ECMAScript 6’s String.prototype.startsWith() method to check a string starts with another string or not. But it is not yet supported in all browsers. Let’s see an example to see this usage,

"Good morning".startsWith("Good"); // true
"Good morning".startsWith("morning"); // false

Q. How do you trim a string in javascript?

JavaScript provided a trim method on string types to trim any whitespaces present at the begining or ending of the string.

"  Hello World   ".trim(); //Hello World

If your browser(<IE9) doesn’t support this method then you can use below polyfill.

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');
        };
    })();
}
↥ back to top

Q. How do you add a key value pair in javascript?

There are two possible solutions to add new properties to an object. Let’s take a simple object to explain these solutions.

var object = {
    key1: value1,
    key2: value2
};
  1. Using dot notation: This solution is useful when you know the name of the property
    object.key3 = "value3";
    
  2. Using square bracket notation: This solution is useful when the name of the property is dynamically determined.
    obj["key3"] = "value3";
    

    Q. How do you assign default values to variables?

    You can use the logical or operator || in an assignment expression to provide a default value. The syntax looks like as below,

    var a = b || c;
    

    As per the above expression, variable ‘a ‘will get the value of ‘c’ only if ‘b’ is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise ‘a’ will get the value of ‘b’.

Q. Can we define properties for functions?

Yes, We can define properties for functions because functions are also objects.

fn = function(x) {
  //Function code goes here
}

fn.name = "John";

fn.profile = function(y) {
  //Profile code goes here
}
↥ back to top

Q. What is the way to find the number of parameters expected by a function?

You can use function.length syntax to find the number of parameters expected by a function. Let’s take an example of sum function to calculate the sum of numbers,

function sum(num1, num2, num3, num4){
    return num1 + num2 + num3 + num4;
}
sum.length // 4 is the number of parameters expected.

Q. What are break and continue statements?

The break statement is used to “jumps out” of a loop. i.e, It breaks the loop and continues executing the code after the loop.

for (i = 0; i < 10; i++) {
  if (i === 5) { break; }
  text += "Number: " + i + "<br>";
}

The continue statement is used to “jumps over” one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

for (i = 0; i < 10; i++) {
    if (i === 5) { continue; }
    text += "Number: " + i + "<br>";
}
↥ back to top

Q. What are js labels?

The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same,

var i, j;

loop1:
for (i = 0; i < 3; i++) {
  loop2:
  for (j = 0; j < 3; j++) {
      if (i === j) {
        continue loop1;
      }
      console.log('i = ' + i + ', j = ' + j);
  }
}

// Output is:
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"

Q. What are the benefits of keeping declarations at the top?

It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,

  1. Gives cleaner code
  2. It provides a single place to look for local variables
  3. Easy to avoid unwanted global variables
  4. It reduces the possibility of unwanted re-declarations

Q. What are the benefits of initializing variables?

It is recommended to initialize variables because of the below benefits,

  1. It gives cleaner code
  2. It provides a single place to initialize variables
  3. Avoid undefined values in the code

Q. What are the recommendations to create new object?

It is recommended to avoid creating new objects using new Object(). Instead you can initialize values based on it’s type to create the objects.

  1. Assign {} instead of new Object()
  2. Assign “” instead of new String()
  3. Assign 0 instead of new Number()
  4. Assign false instead of new Boolean()
  5. Assign [] instead of new Array()
  6. Assign /()/ instead of new RegExp()
  7. Assign function (){} instead of new Function()

You can define them as an example,

var v1 = {};
var v2 = "";
var v3 = 0;
var v4 = false;
var v5 = [];
var v6 = /()/;
var v7 = function(){};
↥ back to top

Q. How do you define JSON arrays?

JSON arrays are written inside square brackets and array contain javascript objects. For example, the JSON array of users would be as below,

"users":[
  {"firstName":"John", "lastName":"Abrahm"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Shane", "lastName":"Warn"}
]

Q. How do you generate random integers?

You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,

Math.floor(Math.random() * 10) + 1;     // returns a random integer from 1 to 10
Math.floor(Math.random() * 100) + 1;     // returns a random integer from 1 to 100

Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

Q. Can you write a random integers function to print integers with in a range?

Yes, you can create a proper random function to return a random number between min and max (both included)

function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
randomInteger(1, 100); // returns a random integer from 1 to 100
randomInteger(1, 1000); // returns a random integer from 1 to 1000

Q. What are the string methods available in Regular expression?

Regular Expressions has two string methods: search() and replace(). The search() method uses an expression to search for a match, and returns the position of the match.

var msg = "Hello John";
var n = msg.search(/John/i); // 6

The replace() method is used return a modified string where the pattern is replaced.

var msg = "Hello John";
var n = msg.search(/John/i, "Buttler"); // Hello Buttler

Q. What are modifiers in regular expression?

Modifiers can be used to perform case-insensitive and global searches. Let’s list down some of the modifiers,

Modifier Description
i Perform case-insensitive matching
g Perform a global match rather than stops at first match
m Perform multiline matching

Let’s take an example of global modifier,

  var text = "Learn JS one by one";
  var pattern = /one/g;
  var result = text.match(pattern); // one,one
↥ back to top

Q. What are regular expression patterns?

Regular Expressions provided group of patterns in order to match characters. Basically they are categorized into 3 types,

1. Brackets: These are used to find a range of characters. For example, below are some use cases,

2. Metacharacters: These are characters with a special meaning For example, below are some use cases,

3. Quantifiers: These are useful to define quantities For example, below are some use cases,

↥ back to top

Q. What is a RegExp object?

RegExp object is a regular expression object with predefined properties and methods. Let’s see the simple usage of RegExp object,

var regexp = new RegExp('\\w+');
console.log(regexp);
// expected output: /\w+/

Q. How do you search a string for a pattern?

You can use test() method of regular expression in order to search a string for a pattern, and returns true or false depending on the result.

var pattern = /you/;
console.log(pattern.test("How are you?")); //true

Q. What is the purpose of exec method?

The purpose of exec method is similar to test method but it returns a founded text as an object instead of returning true/false.

var pattern = /you/;
console.log(pattern.test("How are you?")); //you

Q. How do you change style of a HTML element?

You can change inline style or classname of a HTML element using javascript

  1. ** Using style property:** You can modify inline style using style property
    document.getElementById("title").style.fontSize = "30px";
    
  2. ** Using ClassName property:** It is easy to modify element class using className property
    document.getElementById("title").style.className = "custom-title";
    
↥ back to top

Q. What is a debugger statement?

The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source.

function getProfile() {
// code goes here
debugger;
// code goes here
}

Q. What is the purpose of breakpoints in debugging?

You can set breakpoints in the javascript code once the debugger statement is executed and debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using play button.

Q. Can I use reserved words as identifiers?

No, you cannot use the reserved words as variables, labels, object or function names. Let’s see one simple example,

var else = "hello"; // Uncaught SyntaxError: Unexpected token else

Q. How do you detect a mobile browser without regexp?

You can detect mobile browser by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,

function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
    return true;
  }
else {
    return false;
  }
}
↥ back to top

Q. How do you get the image width and height using JS?

You can programmatically get the image and check the dimensions(width and height) using Javascript.

var img = new Image();
img.onload = function() {
  console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

Q. How do you make synchronous HTTP request?

Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript

function httpGet(theUrl)
{
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttpReq.send( null );
    return xmlHttpReq.responseText;
}

Q. How do you make asynchronous HTTP request?

Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing 3rd parameter as true.

function httpGetAsync(theUrl, callback)
{
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
            callback(xmlHttpReq.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
}
↥ back to top

Q. How do you convert date to another timezone in javascript?

You can use toLocaleString() method to convert date in one timezone to another. For example, let’s convert current date to British English timezone as below,

console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); //29/06/2019, 09:56:00

Q. What are the properties used to get size of window?

You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let’s use them combination of these properties to calculate the size of a window or document,

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Q. What is a conditional operator in javascript?

The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement.

var isAuthenticated = false;
console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated'); //Sorry, you are not authenticated

Q. Can you apply chaining on conditional operator?

Yes, you can apply chaining on conditional operator similar to if … else if … else if … else chain. The syntax is going to be as below,

function traceValue(someParam) {
    return condition1 ? value1
        : condition2 ? value2
        : condition3 ? value3
        : value4;
}

// The above conditional operator is equivalent to:

function traceValue(someParam) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
↥ back to top

Q. What are the ways to execute javascript after page load?

You can execute javascript after page load in many different ways,

  1. window.onload:
    window.onload = function ...
    
  2. document.onload:
    document.onload = function ...
    
  3. body onload: ```html
``` #### Q. What is the difference between proto and prototype? The `__proto__` object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas `prototype` is the object that is used to build `__proto__` when you create an object with new ```javascript ( new Employee ).__proto__ === Employee.prototype; ( new Employee ).prototype === undefined; ``` #### Q. Give an example where do you really need semicolon? It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon. ```javascript // define a function var fn = function () { //... } // semicolon missing at this line // then execute some code inside a closure (function () { //... })(); ``` and it will be interpreted as ```javascript var fn = function () { //... }(function () { //... })(); ``` In this case, we are passing second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.
↥ back to top
#### Q. What is a freeze method? The freeze() method is used to freeze an object. Freezing an object does'nt allow adding new properties to an object,prevents from removing and prevents changing the enumerability, configurability, or writability of existing properties. i.e, It returns the passed object and does not create a frozen copy. ```javascript const obj = { prop: 100 }; Object.freeze(obj); obj.prop = 200; // Throws an error in strict mode console.log(obj.prop); //100 ``` *Note: It causes a TypeError if the argument passed is not an object*. #### Q. What is the purpose of freeze method? Below are the main benefits of using freeze method, 1. It is used for freezing objects and arrays. 2. It is used to make an object immutable. #### Q. Why do I need to use freeze method? In Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as `final` keyword which is used in various languages. #### Q. How do you detect a browser language preference? You can use navigator object to detect a browser language preference as below, ```javascript var language = navigator.languages && navigator.languages[0] || // Chrome / Firefox navigator.language || // All browsers navigator.userLanguage; // IE <= 10 console.log(language); ``` #### Q. How to convert string to title case with javascript? Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function, ```javascript function toTitleCase(str) { return str.replace( /\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); } toTitleCase("good morning john"); // Good Morning John ``` #### Q. How do you detect javascript disabled in the page? You can use `