JavaScript Interview Questions Part 2

What is the difference between .call() and .apply()?

“The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

var someObject = {
myProperty : ‘Foo’,

myMethod : function(prefix, postfix) {

alert(prefix + this.myProperty + postfix);

someObject.myMethod(‘<‘, ‘>’); // alerts ”
var someOtherObject = {

myProperty : 'Bar.'

};, ‘<‘, ‘>’); // alerts ”

someObject.myMethod.apply(someOtherObject, [‘<‘, ‘>’]); // alerts ””

What is event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of the parent will also work as if it were clicked too.

Is JavaScript case sensitive? Give its example.

Yes, JavaScript is case-sensitive. For example, a function parseInt is not the same as the function Parseint.

JavaScript Interview Questions

What boo lean operators can be used in JavaScript?

“The ‘And’ Operator (&&), ‘Or’ Operator (||), and the ‘Not’ Operator (!) can be used in JavaScript.

*Operators are without the parenthesis.”

What is the role of break and continue statements?

The break statement is used to come out of the current loop. In contrast, the continue statement continues the current loop with a new recurrence.

Write the point of difference between a web garden and a web farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server. At the same time web-farm is a larger setup that uses more than one server.

Advance JavaScript Interview Questions

How are object properties assigned?

Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document. form.action=”submit”

What is the method for reading and writing a file in JavaScript?

“This can be done by Using JavaScript extensions (runs from JavaScript Editor), for example, for the opening of a file –

fh = fopen(getScriptPath(), 0); “

How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraphs, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

JavaScript Interview Questions

How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a form by the user. An event handler is required to manage the proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes the event’s name and the action taken if the event takes place.

What is the role of deferred scripts in JavaScript?

“The HTML code’s parsing during page loading is paused by default until the script has not stopped executing. If the server is slow or the script is particularly heavy, then the web page is delayed.

While using Deferred, scripts delays execution of the script till the time the HTML parser is running. This reduces the loading time of web pages, and they get displayed faster.”

What are the various functional components in JavaScript?

“The different functional components in JavaScript are-

First-class functions: Functions in JavaScript are utilized as first-class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables, or can also be stored in data structures.
Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘every time the main function is invoked.”

Advance JavaScript Interview Questions

Write about the errors shown in JavaScript?

“JavaScript gives a message as if it encounters an error. The recognized errors are –

Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. The use of improper syntax encounters these errors and is thus detected while the page is getting loaded.
Runtime errors: This is the error that comes up while the program is running. For example, illegal operations cause the division of a number by zero or access a non-existent area of the memory.
Logic errors: It is caused by syntactically correct code, which does not fulfill the required task—for example, an infinite loop.”

What are Screen objects?

“Screen objects are used to read the information from the client’s screen. The properties of screen objects are –

Avail Height: Gives the height of the client’s screen
Avail Width: Gives the width of the client’s screen
Color Depth: Gives the bit depth of images on the client’s screen
Height: Gives the total height of the client’s screen, including the taskbar
Width: Gives the total width of the client’s screen, including the taskbar”

What is the unshift() method?

“This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –

var name = [ “”john”” ];
name.unshift( “”charlie”” );
name.unshift( “”joseph””, “”Jane”” );
The output is shown below:

[“” joseph ,””,”” Jane ,””, “” charlie “”, “” john “”]”

JavaScript Interview Questions

How are JavaScript and ECMA Script related?

ECMA Script is like rules and guidelines, while Java script is a scripting language used for web development.

What is name spacing in JavaScript, and how is it used?

Name spacing is used for grouping the desired functions, variables, etc., under a unique name. It is a name that has been attached to the desired functions, objects, and properties. This improves modularity in the coding and enables code reuse.

How to use Loop in JavaScript?

Loops are useful when you repeatedly execute the same lines of code a specific number of times or as long as a specific condition is true. Suppose you want to type a ‘Hello’ message 100 times on your webpage. Of course, you will have to copy and paste the same line 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

Advance JavaScript Interview Questions

What is a prototype chain

“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.”

What is the difference between Call, Apply and Bind

“The difference between Call, Apply and Bind can be explained with below examples,

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);
}, ‘Hello’, ‘How are you?’); // Hello John Rodson, How are you?, ‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given this value 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 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?
Call and apply are pretty interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.

Whereas Bind creates a new function that will have this set to the first parameter passed to bind().”

What is JSON and its common operations

“JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crock ford. It is useful when you want to transmit data across a network and it is basically just a text file with an extension of .JSON, and a MIME type of application/JSON

Parsing: Converting a string to a native object

JSON. parse(text)
Stringification: converting a native object to a string so it can be transmitted across the network

JSON. stringify (object)”

JavaScript Interview Questions

How do you compare Object and Map

“Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases.

The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
The keys in Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.
You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
An Object has a prototype, so there are default keys in the map that could collide with your keys if you’re not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.
A Map may perform better in scenarios involving frequent addition and removal of key pairs.”

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,


What are 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 has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

Advance JavaScript Interview Questions

How do you receive server-sent event notifications

“The Event Source object is used to receive server-sent event notifications. For example, you 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 += + “”

What are the main rules of promise

“A promise must follow a specific set of rules,

A promise is an object that supplies a standard-compliant .then() method
A pending promise may transition into either fulfilled or rejected state
A fulfilled or rejected promise is settled and it must not transition into any other state.
Once a promise is settled, the value must not change.”

How do style the console output using CSS?

“You can add CSS styling to the console output using the CSS format content specifier %c. The console string message can be appended after the specifier and CSS style in another argument. Let’s print the red the color text using console.log and CSS specifier as below,

console.log(“”%cThis is a red text””, “”color:red””);
It is also possible to add more styles for the content. For example, the font-size can be modified for the above text

console.log(“”%cThis is a red text with bigger font””, “”color:red; font-size:20px””);”

JavaScript Interview Questions

What is the easiest way to ignore promise errors?

“The easiest and safest way to ignore promise errors is void that error. This approach is ESLint friendly too.

await promise.catch(e => void e);”

Is that possible to use expressions in switch cases?

“You might have seen expressions used in switch condition but it is also possible to use for switch cases by assigning true value for the switch condition. Let’s see the weather condition based on temparature as an example,
const weather = function getWeather(temp) {
switch(true) {
case temp < 0: return ‘freezing’;
case temp < 10: return ‘cold’;
case temp < 24: return ‘cool’;
default: return ‘unknown’;

How to invoke an IIFE without any extra brackets?

“Immediately Invoked Function Expressions(IIFE) requires a pair of parenthesis to wrap the function which contains set of statements.

(function(dt) {
})(new Date());
Since both IIFE and void operator discard the result of an expression, you can avoid the extra brackets using void operator for IIFE as below,

void function(dt) {
}(new Date()); “

Advance JavaScript Interview Questions

What is the difference between isNaN and Number.isNaN?

“isNaN: The global function isNaN converts the argument to a Number and returns true if the resulting value is NaN.
Number.isNaN: This method does not convert the argument. But it returns true when the type is a Number and value is NaN.
Let’s see the difference with an example,

isNaN(‘hello’); // true
Number.isNaN(‘hello’); // false”

How do you define instance and non-instance properties

“The Instance properties must be defined inside of class methods. For example, name and age properties defined insider constructor as below,

class Person {
constructor(name, age) { = name;
this.age = age;
But Static(class) and prototype data properties must be defined outside of the ClassBody declaration. Let’s assign the age value for Person class as below,

Person.staticAge = 30;
Person.prototype.prototypeAge = 40;”

What are the differences between for…of and for…in statements

“Both for…in and for…of statements iterate over js data structures. The only difference is over what they iterate: iterates over all enumerable property keys of an object
for..of iterates over the values of an iterable object.
Let’s explain this difference with an example,

let arr = [‘a’, ‘b’, ‘c’];

arr.newProp = ‘newVlue’;

// key are the property keys
for (let key in arr) {

// value are the property values
for (let value of arr) {
Since loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of loop iterates over the values of a arr data structure and logs a, b, c in the console.”

JavaScript Interview Questions

What are the built-in iterables

“Below are the list of built-in iterables in JavaScript,

Arrays and Typed Arrays
Strings: Iterate over each character or Unicode code-points
Maps: iterate over its key-value pairs
Sets: iterates over their elements
arguments: An array-like special variable in functions
DOM collection such as Node List”

What are the differences between arguments object and rest parameter

“There are three main differences between arguments object and rest parameters

The arguments object is an array-like but not an array. Whereas the rest parameters are array instances.
The arguments object does not support methods such as sort, map, forEach, or pop. Whereas these methods can be used in rest parameters.
The rest parameters are only the ones that haven’t been given a separate name, while the arguments object contains all arguments passed to the function”

How to detect if a function is called as constructor

“You can use new. Target pseudo-property to detect whether a function was called as a constructor(using the new operator) or as a regular function call.

If a constructor or function invoked using the new operator, returns a reference to the constructor or function.
For function calls, is undefined.
function Myfunc() {
if ( {
console.log(‘called with new’);
} else {
console.log(‘not called with new’);

new Myfunc(); // called with new
Myfunc(); // not called with new{}); not called with new”

Advance JavaScript Interview Questions

How do you check an object is a promise or not

“If you don’t know if a value is a promise or not, wrapping the value as Promise. Resolve(value) which returns a promise

function isPromise(object){
if(Promise && Promise.resolve){
return Promise.resolve(object) == object;
throw “”Promise not supported in your environment””

var i = 1;
var promise = new Promise(function(resolve,reject){

console.log(isPromise(i)); // false
console.log(isPromise(p)); // true
Another way is to check for .then() handler type

function isPromise(value) {
return Boolean(value && typeof value.then === ‘function’);
var i = 1;
var promise = new Promise(function(resolve,reject){

console.log(isPromise(i)) // false
console.log(isPromise(promise)); // true”

What is a Proper Tail Call

“First, we should know about tail call before talking about “”Proper Tail Call””. A tail call is a subroutine or function call performed as the final action of a calling function. Whereas Proper tail call(PTC) is a technique where the program or code will not create additional stack frames for a recursion when the function call is a tail call.

For example, the below classic or head recursion of factorial function relies on stack for each step. Each step need to be processed upto n * factorial(n – 1)

function factorial(n) {
if (n === 0) {
return 1
return n * factorial(n – 1)
console.log(factorial(5)); //120
But if you use Tail recursion functions, they keep passing all the necessary data it needs down the recursion without relying on the stack.

function factorial(n, acc = 1) {
if (n === 0) {
return acc
return factorial(n – 1, n * acc)
console.log(factorial(5)); //120
The above pattern returns the same output as the first one. But the accumulator keeps track of total as an argument without using stack memory on recursive calls.”

How do you make an object iterable in JavaScript

“By default, plain objects are not iterable. But you can make the object iterable by defining a Symbol.iterator property on it.

Let’s demonstrate this with an example,

const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > values.length

const iterator = collection[Symbol.iterator]();

console.log(; // → {value: 1, done: false}
console.log(; // → {value: 2, done: false}
console.log(; // → {value: 3, done: false}
console.log(; // → {value: undefined, done: true}
The above process can be simplified using a generator function,

const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]: function * () {
for (let key in this) {
yield this[key];
const iterator = collection[Symbol.iterator]();
console.log(; // {value: 1, done: false}
console.log(; // {value: 2, done: false}
console.log(; // {value: 3, done: false}
console.log(; // {value: undefined, done: true}”

JavaScript Interview Questions

What is Deno

Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 JavaScript engine and the Rust programming language.

How do you prevent promises swallowing errors

“While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.

Let’s say you expect to print an error to the console for all the below cases,

Promise.resolve(‘promised value’).then(function() {
throw new Error(‘error’);

Promise.reject(‘error value’).catch(function() {
throw new Error(‘error’);

new Promise(function(resolve, reject) {
throw new Error(‘error’);
But there are many modern JavaScript environments that won’t print any errors. You can fix this problem in different ways,

Add catch block at the end of each chain: You can add catch block to the end of each of your promise chains

Promise.resolve(‘promised value’).then(function() {
throw new Error(‘error’);
}).catch(function(error) {
But it is quite difficult to type for each promise chain and verbose too.

Add done method: You can replace first solution’s then and catch blocks with done method

Promise.resolve(‘promised value’).done(function() {
throw new Error(‘error’);
Let’s say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously. You can write done block as below,

.then(function(result) {
return processDataAsync(result);
.done(function(processed) {
In future, if the processing library API changed to synchronous then you can remove done block as below,

.then(function(result) {
return displayData(processDataAsync(result));
and then you forgot to add done block to then block leads to silent errors.

Extend ES6 Promises by Bluebird: Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a “default” onRejection handler which will print all errors from rejected Promises to stderr. After installation, you can process unhandled rejections

throw error;
and discard a rejection, just handle it with an empty catch

Promise.reject(‘error value’).catch(function() {});”

What is an a sync function

“An async function is a function declared with the async keyword which enables asynchronous, promise-based behavior to be written in a cleaner style by avoiding promise chains. These functions can contain zero or more await expressions.

Let’s take a below async function example,

async function logger() {

let data = await fetch(‘’); // pause until fetch returns
It is basically syntax sugar over ES2015 promises and generators.”

Advance JavaScript Interview Questions

What is the difference between function and class declarations

“The main difference between function declarations and class declarations is hoisting. The function declarations are hoisted but not class declarations.


const user = new User(); // ReferenceError

class User {}
Constructor Function:

const user = new User(); // No error

function User() {

What is an observable

“An Observable is basically a function that can return a stream of values either synchronously or asynchronously to an observer over time. The consumer can get the value by calling subscribe() method. Let’s look at a simple example of an Observable

import { Observable } from ‘rxjs’;

const observable = new Observable(observer => {
setTimeout(() => {‘Message from a Observable!’);
}, 3000);

observable.subscribe(value => console.log(value));”

What is the easiest way to resize an array

“The length property of an array is useful to resize or empty an array quickly. Let’s apply length property on number array to resize the number of elements from 5 to 2,

var array = [1, 2, 3, 4, 5];
console.log(array.length); // 5

array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
and the array can be emptied too

var array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []”

JavaScript Interview Questions

What is a Short circuit condition

“Short circuit conditions are meant for condensed way of writing simple if statements. Let’s demonstrate the scenario using an example. If you would like to login to a portal with an authentication condition, the expression would be as below,

if (authenticate) {
Since the javascript logical operators evaluated from left to right, the above expression can be simplified using && logical operator

authenticate && loginToPorta();”

What is the difference between Function constructor and function declaration

“The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e., the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.

Let’s see this difference with an example,

Function Constructor:

var a = 100;
function createFunction() {
var a = 200;
return new Function(‘return a;’);
console.log(createFunction()()); // 100
Function declaration:

var a = 100;
function createFunction() {
var a = 200;
return function func() {
return a;
console.log(createFunction()()); // 200″

What is RxJS

RxJS (Reactive Extensions for JavaScript) is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback-based code. It also provides utility functions for creating and working with observables.

Advance JavaScript Interview Questions

What are the common use cases of observables

Some of the most common use cases of observables are web sockets with push notifications, user input changes, repeating intervals, etc.

Is Node.js completely single threaded

Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e. Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.

JavaScript Part 1JavaScript Part 3
Back to top