Javascript Interview Question Flashcards

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

Object constructor:
var object = new Object();

Object’s create method:

var object = Object.create(null);

Object literal syntax:
var object = {
name: “Sudheer”,
age: 34
};

Function constructor:

function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person(“Sudheer”);

Function constructor with prototype:

function Person() {}
Person.prototype.name = “Sudheer”;
var object = new Person();

ES6 Class syntax

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

var object = new Person(“Sudheer”);

Singleton pattern

var object = new (function () {
this.name = “Sudheer”;
})();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

1.A What is object constructor? Using Constructor object create object.

A

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

The Object constructor turns the input into an object. Its behaviour depends on the input’s type.

const o = new Object();
o.foo = 42;
console.log(o);
// Object { foo: 42 }

Object() can be called with or without new. Both create a new object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

1.B What is Object’s create method?

A

The create method of Object creates a new object by passing the prototype object as a parameter.
var object = Object.create(null);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

1.C What is Object literal syntax?

A

The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.

var object = {
name: “Sudheer”,
age: 34
};

Object literal property values can be of any data type, including array, function, and nested object.

Note: This is an easiest way to create an object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

1.D What is Function constructor? What are the basic rules of constructor function?

A

Create any function and apply the new operator to create object instances,
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person(“Sudheer”);

Remember: Contractor function always starts with a Capital and has to be Titlecased.

Rules:
1. Use “this” keyword to store the data.
2. Title casing for the function
3. using new, else the object assigned won’t be assinged to this.
4. Using bind, in the closures of the prototype functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

1.D.A What are the basic rules of Function constructor:

A

Rules:
1. Use “this” keyword to store the data.
2. Title casing for the function
3. using new, else the object assigned won’t be assinged to this.
4. Using bind, in the closures of the prototype functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

1.E How to use prototype in function constructor?

A

This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {}
Person.prototype.name = “Sudheer”;
var object = new Person();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

1.F How to create object with ES6 Class Syntax?

A

ES6 introduces a class feature to create the objects, so using constructor.

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

var object = new Person(“Sudheer”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

1.G How to create object using Singleton Pattern?

A

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 = “Sudheer”;
})();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
  1. What is a prototype chain?
A

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.

let human = { mortal: true }
let socrates = Object.create(human)
socrates.age = 45
console.log(human.isPrototypeOf(socrates))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
  1. What is the difference between Call, Apply and Bind?
A

The difference between Call, Apply and Bind can be explained with the below examples:
Call: The call() method invokes a function with a given this value and arguments provided one by one
Apply: Invokes the function with a given this value and allows you to pass in arguments as an array
bind: returns a new function, allowing you to pass any number of arguments.

Example:
var employee1 = { firstName: “John”, lastName: “Rodson” };
var employee2 = { firstName: “Jimmy”, lastName: “Baily” };

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

Call:
invite.call(employee1, “Hello”, “How are you?”); // Hello John Rodson, How are you?

Apply:
invite.apply(employee1, [“Hello”, “How are you?”]); // Hello John Rodson, How are you?

Bind:
var inviteEmployee1 = invite.bind(employee1);
inviteEmployee1(“Hello”, “How are you?”); // Hello John Rodson, How are you?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

3.A What is call() in Function prototype?

A

The call() method calls the function with a given “this” value and arguments provided individually.

Example:

function Product(name, price) {
this.name = name;
this.price = price;
}

function Food(name, price) {
Product.call(this, name, price);
this.category = ‘food’;
}

console.log(new Food(‘cheese’, 5).name);
// expected output: “cheese”

Here we are assigning product to food with call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

3.B What does bind argument do in general?

A

The bind() method creates a new function that, when called, has its “this” keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  1. What is JSON and its common operations?
A

JSON is a text-based data format following JavaScript object syntax,
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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
  1. What is the difference between slice and splice?
A

Slice
Doesn’t modify the original array(immutable)
Returns the subset of the original array
Used to pick the elements from an array

Splice
Modifies the original array(mutable)
Returns the deleted elements as an array
Used to insert or delete elements to/from an array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. How do you compare Object and Map?
A

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.

Differences:
1. The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
2. 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.
3. 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.
4. A Map is iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
5. 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.
6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q
  1. What is the difference between == and === operators?
A

Equality comparison. Because of coercion is always better and recommend to using ===
Strict(===, !==)
Type-converting(==, !=)

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q
  1. What are lambda or arrow functions?
A
  1. An arrow function is a shorter syntax for a function expression
  2. Do not have its own this, arguments, super, or new.target.
  3. These functions are best suited for non-method functions, and they cannot be used as constructors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

10.A What is new.target?

A

The new.target pseudo-property lets you detect whether a function or constructor was called using the new operator.

function Foo() {
if (!new.target) { throw ‘Foo() must be called with new’; }
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

10.B What is super?

A

The super keyword is used to access properties on an object literal or class’s [[Prototype]], or invoke a superclass’s constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
  1. What is a first class function?
A

In Javascript, functions are first-class objects. First-class functions mean when functions in that language are treated like any other variable.

For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener.

Example:
const handler = () => console.log(“This is a click handler function”);
document.addEventListener(“click”, handler);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
  1. What is a first order function?
A

The first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.

const firstOrder = () => console.log(“I am a first order function!”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q
  1. What is a higher order function?
A

Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.

const firstOrderFunc = () =>
console.log(“Hello, I am a First order function”);
const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
  1. What is a unary function?
A

A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
  1. What is the currying function?
A

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. Currying is named after mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function.

Example for normal function:
const multiArgFunction = (a, b, c) => a + b + c;
console.log(multiArgFunction(1, 2, 3)); // 6

Example of curry function:
const curryUnaryFunction = (a) => (b) => (c) => a + b + c;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

15.A What is the use of currying function

A

Curried functions are great to improve code reusability and functional composition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q
  1. What is a pure function?
A

A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments ‘n’ number of times and ‘n’ number of places in the application then it will always return the same value.

Let’s take an example to see the difference between pure and impure functions,

//Impure
let numberArray = [];
const impureAddNumber = (number) => numberArray.push(number);

//Pure
const pureAddNumber = (number) => (argNumberArray) =>
argNumberArray.concat([number]);

//Display the results
console.log(impureAddNumber(6)); // returns 1
console.log(numberArray); // returns [6]
console.log(pureAddNumber(7)(numberArray)); // returns [6, 7]
console.log(numberArray); // returns [6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

16.A What is the purpose for pure function?

A

Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the Immutability concept of ES6 by giving preference to const over let usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q
  1. What is the purpose of the let keyword?
A

The let statement declares a block scope local variable. Hence the variables defined with “let” keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the var keyword are used to define a variable globally, or locally to an entire function regardless of block scope.

let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // 31
}
console.log(counter); // 30 (because the variable in if block won’t exist here)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q
  1. What is the difference between let and var?
A

var let
It is been available from the beginning of JavaScript
It has function scope
Variables will be hoisted

let
Introduced as part of ES6
It has block scope
Hoisted but not initialized

Example:
function userDetails(username) {
if (username) {
console.log(salary); // undefined due to hoisting
console.log(age); // ReferenceError: Cannot access ‘age’ before initialization
let age = 30;
var salary = 10000;
}
console.log(salary); //10000 (accessible to due function scope)
console.log(age); //error: age is not defined(due to block scope)
}
userDetails(“John”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q
  1. How do you redeclare variables in switch block without an error?
A

Instead of

case 0:
let name;

using a block

case 0: {
let name
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q
  1. What is the Temporal Dead Zone?
A

The Temporal Dead Zone is a behaviour in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var.
In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError.
The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q
  1. What is IIFE(Immediately Invoked Function Expression)?
A

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function () {
// logic here
})();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

22A. What is the purpose of IIFE?

A

The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables with IIFE then it throws an error as below,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q
  1. How do you decode or encode a URL in JavaScript?
A

encodeURI()
decodeURI()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q
  1. What is memoization?
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q
  1. What is Hoisting?
A

Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.

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

In the same fashion, function declarations are hoisted too

message(“Good morning”); //Good morning

function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q
  1. What are classes in ES6?
A

In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,

function Bike(model, color) {
this.model = model;
this.color = color;
}

Bike.prototype.getDetails = function () {
return this.model + “ bike has” + this.color + “ color”;
};

Whereas ES6 classes can be defined as an alternative

class Bike {
constructor(color, model) {
this.color = color;
this.model = model;
}

getDetails() {
return this.model + “ bike has” + this.color + “ color”;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q
  1. What are closures?
A

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

  1. Own scope where variables defined between its curly brackets
  2. Outer function variables
  3. Global variables

Example:

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(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q
  1. What are modules?
A

Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns.
Most of the JavaScript modules export an object literal, a function, or a constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q
  1. Why do we need modules?
A

Maintainability
Reusability
Namespacing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q
  1. What is scope in Javascript?
A

The scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q
  1. What is a service worker?
A

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don’t need a web page or user interaction.
Some of the major features of service workers are Rich offline experiences(offline-first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q
  1. How do you manipulate DOM using a service worker?
A

The service workers can’t access the DOM directly.

But it can communicate with the pages it controls by responding to messages sent via the “postMessage” interface, and those pages can manipulate the DOM.

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

Service workers will have access to IndexedDB API in order to persist and reuse across restarts.

However, The problem with the service worker is that it gets terminated when not in use, and restarted when it’s next needed, so you cannot rely on the global state within a service worker’s onfetch and onmessage handlers.

46
Q
  1. What is IndexedDB?
A

IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

47
Q
  1. What is web storage?
A

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user’s browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.

  1. Local storage: It stores data for current origin with no expiration date.
  2. Session storage: It stores data for one session and the data is lost when the browser tab is closed.
48
Q
  1. What is a post message?
A

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 the same-origin policy(i.e, pages share the same protocol, port number, and host).

49
Q
  1. What is a Cookie?
A

A cookie is a piece of data that is stored on your computer to be accessed by your browser.
Cookies are saved as key/value pairs.

50
Q
  1. Why do you need a Cookie?
A

Cookies are used to remember information about the user profile(such as username). It basically involves two steps,

  1. When a user visits a web page, the user profile can be stored in a cookie.
  2. Next time the user visits the page, the cookie remembers the user profile.
51
Q
  1. What are the options in a cookie?
A

By default,
1. the cookie is deleted when the browser is closed
2. the cookie belongs to a current page.

Behaviour can be changed by settings.
document.cookie = “username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC”;
document.cookie = “username=John; path=/services”;

52
Q
  1. How do you delete a cookie?
A
  1. You can delete a cookie by setting the expiry date as a passed date. You don’t need to specify a cookie value in this case.
53
Q
  1. What are the differences between cookie, local storage and session storage?
A

Feature Cookie Local storage Session storage
Accessed on client or server side Both server-side & client-side client-side only client-side only
Lifetime As configured using Expires option until deleted until tab is closed
SSL support Supported Not supported Not supported
Maximum data size 4KB 5 MB 5MB

54
Q
  1. What is the main difference between localStorage and sessionStorage?
A

LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.

55
Q
  1. How do you access web storage?
A

The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local). For example, you can read and write on local storage objects as below

localStorage.setItem(“logo”, document.getElementById(“logo”).value);
localStorage.getItem(“logo”);

56
Q
  1. What are the methods available on session storage?
A

The session storage provided methods for reading, writing and clearing the session data

// Save data to sessionStorage
sessionStorage.setItem(“key”, “value”);

// Get saved data from sessionStorage
let data = sessionStorage.getItem(“key”);

// Remove saved data from sessionStorage
sessionStorage.removeItem(“key”);

// Remove all saved data from sessionStorage
sessionStorage.clear();

57
Q
  1. What is a storage event and its event handler?
A

The storage event of the Window interface fires when a storage area (localStorage) has been modified in the context of another document.

Example:
addEventListener(‘storage’, (event) => { });
onstorage = (event) => { };

Elements:
key
newValue
oldValue
storageArea
url

58
Q
  1. Why do you need web storage?
A

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.

59
Q
  1. How do you check web storage browser support?
A

You need to check browser support for localStorage and sessionStorage before using web storage,

if (typeof Storage !== “undefined”) {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

60
Q
  1. How do you check web workers browser support?
A

if (typeof Worker !== “undefined”) {
// code for Web worker support.
} else {
// Sorry! No Web Worker support..
}

61
Q
  1. Give an example of a web worker?
A

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

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

w.terminate();
w = undefined;

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

WebWorkers don’t have access to the below javascript objects:

Window object
Document object
Parent object

63
Q
  1. What is a promise?
A

A promise is an object that may produce a single value sometime 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.

The syntax of Promise creation looks like below,

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

The usage of a promise would be as below,

const promise = new Promise(
(resolve) => {
setTimeout(() => {
resolve(“I’m a Promise!”);
}, 5000);
},
(reject) => {}
);
promise.then((value) => console.log(value));

64
Q
  1. Why do we need promise?
A

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

65
Q
  1. What are the three states of promise?
A

Promises have three states:

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

66
Q
  1. What is a callback function?
A

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. Let’s take a simple example of how to use a callback function

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

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

outerFunction(callbackFunction);

67
Q
  1. Why do we need callback functions?
A

The callbacks are needed because javascript is an event-driven language.
That means instead of waiting for a response javascript will keep executing while listening for other events.

Example:
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

Javascript didn’t wait for the response of the first function and the remaining code block got executed.
So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.

68
Q
  1. What is a callback hell?
A

Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic.

async1(function(){
async2(function(){
async3(function(){
async4(function(){
….
});
});
});
});

69
Q
  1. What are server-sent events?
A

Identically to WebSockets in part of handling incoming events.
This is a one-way connection, so you can’t send events from a client to a server.
HTTP connection without resorting to polling.
This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

70
Q
  1. How do you receive server-sent event notifications?
A

The EventSource 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 += event.data + “<br></br>”;
};
}

71
Q
  1. What are the events available for server sent events?
A

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

72
Q
  1. What are the main rules of promise?
A

A promise must follow a specific set of rules,

  1. A promise is an object that supplies a standard-compliant .then() method
  2. A pending promise may transition into either fulfilled or rejected the state
  3. A fulfilled or rejected promise is settled and it must not transition into any other state.
  4. Once a promise is settled, the value must not change.
73
Q
  1. What is callback in callback?
A

You can nest one callback inside another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.
If this continues it’s called callback for hell.

74
Q
  1. What is promise chaining?
A

The process of executing a sequence of asynchronous tasks one after another using promise is known as Promise chaining. Let’s take an example of promise chaining for calculating the final result,

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;
});

75
Q
  1. What is promise.all?
A

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.

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

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

Promise.race() method will return the promise instance which is firstly resolved or rejected.

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
});

77
Q
  1. What is a strict mode in javascript?
A

Strict Mode is a new feature in ECMAScript 5 that allows you 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.

78
Q
  1. Why do you need strict mode?
A

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.

79
Q
  1. How do you declare strict mode?
A

The strict mode is declared by adding “use strict”; to the beginning of a script or a function. If declared 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

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

function myFunction() {
“use strict”;
y = 3.14; // This will cause an error
}

80
Q
  1. What is the purpose of double exclamation?
A

The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsely (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.

For example, you can test IE version using this expression below,

let isIE8 = false;
isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false

If you don’t use this expression then it returns the original value.
The expression !! is not an operator, but it is just twice of ! operator.

81
Q
  1. What is the purpose of the delete operator?
A

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”}

82
Q
  1. What is typeof operator?
A

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”

83
Q
  1. What is undefined property?
A

The undefined property indicates that a variable has not been assigned a value or declared but is not initialized.
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;

84
Q
  1. What is null value?
A

The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values. The type of null value is an object. You can empty the variable by setting the value to null.

var user = null;
console.log(typeof user); //object

85
Q
  1. What is the difference between null and undefined?
A

Null
It is an assignment value which indicates that variable points to no object.
Type of null is object
The null value is a primitive value that represents the null, empty, or non-existent reference.
Indicates the absence of a value for a variable
Converted to zero (0) while performing primitive operations

Undefined
It is not an assignment value where a variable has been declared but has not yet been assigned a value.
Type of undefined is undefined
The undefined value is a primitive value used when a variable has not been assigned a value.
Indicates absence of variable itself
Converted to NaN while performing primitive operations

86
Q
  1. What is eval?
A

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

87
Q
  1. What is the difference between window and document?
A

Window:
It is the root level element in any web page
By default window object is available implicitly in the page
It has methods like alert(), confirm() and properties like document, location

Document:
It is the direct child of the window object. This is also known as Document Object Model(DOM)
You can access it via window.document or document.
It provides methods like getElementById, getElementsByTagName, createElement etc

88
Q
  1. How do you access history in javascript?
A

The window.history object contains the browser’s 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 a window prefix.

89
Q
  1. How do you detect caps lock key turned on or not?
A

getModifierState

“CapsLock” - For capital.
“ScrollLock”
“NumLock”

90
Q
  1. What is isNaN?
A

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

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

undeclared:
These variables do not exist in a program and are not declared
If you try to read the value of an undeclared variable, then a runtime error is encountered

undefined:
These variables are declared in the program but have not been assigned any value
If you try to read the value of an undefined variable, an undefined value is returned.

92
Q
  1. What are global variables?
A

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

93
Q
  1. What are the problems with global variables?
A

Conflict of varaibles:
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.

Memory usage:
If there are more number of global variables.

94
Q
  1. What is NaN property?
A

The NaN property is a global property that represents the “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 a few cases

Math.sqrt(-1);
parseInt(“Hello”);

95
Q
  1. What is the purpose of isFinite function?
A

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

96
Q
  1. What is an event flow?
A

Event flow is the order in which an 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 for each of its parent elements first, starting at the top with the global window object.

There are two ways of event flow

  1. Top to Bottom(Event Capturing)
  2. Bottom to Top (Event Bubbling), Default
97
Q
  1. What is event bubbling?
A

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.

It’s a default event flow.

98
Q
  1. What is event capturing?
A

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 innermost DOM element.

Example:
<div>
<h2>Welcome To GFG</h2>
<div>GrandParent
<div>Parent
<div> Child</div>
</div>
</div>
</div>

    const grandParent = document.getElementById("grandparent");
    const parent = document.getElementById("parent");
    const child = document.getElementById("child");
     
    // Changing value of capture parameter as 'true'
    grandParent.addEventListener("click", (e) => {
        console.log("GrandParent");
    }, { capture: true });
    parent.addEventListener("click", (e) => {
        console.log("Parent");
    }, { capture: true });
    child.addEventListener("click", (e) => {
        console.log("Child");
    }, { capture: true });
99
Q
  1. How do you submit a form using Javascript?
A

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

function submit() {
document.forms[0].submit();
}

100
Q
  1. How do you find operating system details?
A

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

console.log(navigator.platform);

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

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).

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

Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification.
For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec.

Host objects are objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc are considered host objects.

User objects are objects defined in the javascript code. For example, User objects that are created for profile information.

103
Q
  1. What are the tools or techniques used for debugging JavaScript code?
A

Chrome Devtools
debugger statement
Good old console.log statement

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

Below is the list of pros and cons of promises over callbacks,

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

Cons:
It makes little complex code
You need to load a polyfill if ES6 is not supported

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

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,

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 evening
console.log(input.value); // Good evening

106
Q
  1. What is same-origin policy?
A

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).

107
Q
  1. What is the purpose of void 0?
A

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 documents that use 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.</a>

But this behaviour will be prevented using this expression. For example, the below link notify the message without reloading the page

</a><a>
Click Me!
</a>

108
Q
  1. Is JavaScript a compiled or interpreted language?
A

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.

109
Q
  1. Is JavaScript a case-sensitive language?
A