Download as pdf or txt
Download as pdf or txt
You are on page 1of 327

Key

JavaScript
JavaScript
Concepts for Interviews
*Disclaimer*
Everyone learns uniquely.

What matters is your preparation and


consistency.

With this doc understand the major


Javascript concepts and ace your next
interview.
EASY
How do you detect primitive or non-
Q.1
primitive value types in Javascript?

In JavaScript, values are generally categorized as either primitive or

non-primitive (also known as reference types). Primitive values

include:

9/ Number: Represents numeric values.

P/ String: Represents textual data.

V/ Boolean: Represents true or false.

/ Undefined: Represents an uninitialized variable or absence of a

value.

Ÿ/ Null: Represents the intentional absence of any object value.

·/ Symbol: Represents a unique identifier.

Non-primitive values are objects, which include arrays, functions,

and custom objects.

We can detect primitive or non primitive in Javascript in the

following ways:

9/ Using the typeof operator:

! This operator returns a string indicating the type of a value.

! Primitive types will return their corresponding strings (e.g.,

"number", "string", "boolean").

! Non-primitive types will typically return "object" or "function".


EASY
Javascript
// Using the typeof operator:

let num = 10;

let str = "Hello";

let bool = true;

let obj = {};

let func = function() {};

console.log(typeof num); // Output: "number"

console.log(typeof str); // Output: "string"

console.log(typeof bool); // Output: "boolean"

console.log(typeof obj); // Output: "object"

console.log(typeof func); // Output: "function"

Important note:
typeof null returns "object" even though it's a primitive value.
EASY
 Using the Object() constructor:
9 This constructor creates a new object wrapper for a value.6
9 If a value is primitive, it will be equal to its object-wrapped
version.6
9 If a value is non-primitive, it won't be equal to its object-wrapped
version.
Javascript
// Using the Object() constructor:

console.log(num === Object(num)); // Output: true


(primitive)

console.log(obj === Object(obj)); // Output: false


(non-primitive)
EASY
Q.2 Explain the key features introduced in
Javascript ES6
In ES6, JavaScript introduced these key features:
VM Arrow FunctionsG
F Concise syntax for anonymous functions with lexical scoping.
jM Template LiteralsG
F Enables multiline strings and variable inclusion for improved
readability.
¦M Destructuring AssignmentG
F Simplifies extraction of values from arrays or objects.
ÈM Enhanced Object LiteralsG
F Introduces shorthand notation for defining object methods and
dynamic property names.
òM PromisesG
F Streamlines asynchronous programming with a cleaner, structured
approach.
EASY
Q.3 What are the differences between var,
const & let in JavaScript?
Attribute var let const

Scope Functional
Block scope Block scope
scope

Can be
Can be updated Cannot be
Update/
updated and
but cannot be re- updated or re-
Re-declaration re-declared declared within declared within
within the scope the scope the scope

Declaration
Can be declared Can be declared Cannot be
without without being without being declared without
Initialization initialized initialized being initialized

Accessible Inaccessible Inaccessible


Access without without without
without initialization initialization initialization
Initialization (default: (throws (throws
undefined) 'ReferenceError') 'ReferenceError')

Hoisted but not Hoisted but not


Hoisted and initialized (error if initialized (error if
Hoisting initialized with a accessed before accessed before
'default' value declaration/ declaration/
initialization) initialization)
MEDIUM
Q.4 What are arrow functions in
Javascript?
Arrow functions are a concise way to write anonymous function
expressions in JavaScript. They were introduced in ECMAScript 6
(ES6) and are especially useful for short, single-expression functions.

Here's the basic syntax for an arrow function:


Javascript
const add = (a, b) => {

return a + b;

};

In this example, the arrow function add takes two parameters (a and
b) and returns their sum. The => syntax is used to define the function,
and the body of the function is enclosed in curly braces {}. If there's
only one expression in the function body, you can omit the curly
braces and the return keyword:
Javascript
const add = (a, b) => {

return a + b;

};
MEDIUM
Here is an example showing how both traditional function expression
and arrow function to illustrate the difference in handle the this
keyword.

Traditional Function Expression:


Javascript

// Define an object

let obj1 = {

value: 42,

valueOfThis: function() {

return this.value; // 'this' refers to the object


calling the function (obj1)

};

// Call the method

console.log(obj1.valueOfThis()); // Output: 42

In this example, obj1.valueOfThis() returns the value property of


obj1, as this inside the function refers to the object obj1.
MEDIUM

Arrow Function:

Javascript

// Define another object

let obj2 = {

value: 84,

valueOfThis: () => {

return this.value; // 'this' does not refer to

obj2; it inherits from the parent scope (window in

this case)

};

// Call the method

console.log(obj2.valueOfThis()); // Output: undefined

or an error (depending on the environment)

In the arrow function within obj2, this does not refer to obj2. Instead,

it inherits its value from the parent scope, which is the global object

(window in a browser environment). Consequently,

obj2.valueOfThis() returns undefined or may even throw an

error, as this.value is not defined in the global scope.


MEDIUM
Q.5 What is hoisting in Javascript?
In JavaScript, hoisting is a phenomenon where variable and function
declarations are conceptually moved to the top of their respective
scopes, even if they're written later in the code. This behaviour
applies to both global and local scopes.

Here are some examples to illustrate hoisting:


Example 1: Variable Hoisting
Javascript
console.log(myMessage); // Outputs "undefined", not
an error

var myMessage = "Greetings!";

While myMessage appears declared after its use, it's hoisted to the
top of the scope, allowing its reference (but not its initial value) before
the actual declaration line.
Example 2: Function Hoisting
Javascript
sayHello(); // Outputs "Hello, world!"

function sayHello() {

console.log("Hello, world!");

}
MEDIUM

Even though sayHello is defined after its call, JavaScript acts as if it

were declared at the beginning of the scope, enabling its execution.

Example 3: Hoisting within Local Scopes

Javascript

function performTask() {

result = 100; // Hoisted within the function

console.log(result); // Outputs 100

var result;

performTask();

Hoisting also occurs within local scopes, like functions. Here, result

is hoisted to the top of the performTask function, allowing its use

before its explicit declaration.

Key Points:

» Only declarations are hoisted, not initializations. The example with

console.log(x); demonstrates this, as x is declared but not

initialised before its use, resulting in undefined.¦

» Strict mode enforces declaration: Using "use strict"; at the

beginning of your code prevents using variables before they're

declared, helping avoid potential hoisting-related issues.


EASY
Q.6 What is Strict Mode in Javascript?
Strict Mode is a feature 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.

Strict mode helps in writing "secure" JavaScript by notifying "bad


syntax" into real errors.

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.
Example:
Javascript
'use strict';

x = 15; // ReferenceError: x is not defined

function strict_function() {

'use strict';

x = 'Test message';

console.log(x);

strict_function(); // ReferenceError: x is not defined


EASY
Q.7 What is NaN?
The NaN property in JavaScript represents a value that is "Not-a-
Number," indicating an illegal or undefined numeric value. When
checking the type of NaN using the typeof operator, it returns
"Number."

To determine if a value is NaN, the isNaN() function is employed. It


converts the given value to a Number type and then checks if it
equals NaN.
Example:
isNaN("Hello"); // Returns true, as "Hello" cannot be converted to a
valid number
isNaN(NaN); // Returns true, as NaN is, by definition, Not-a Number
isNaN("123ABC"); // Returns true, as "123ABC" cannot be converted
to a valid number
isNaN(undefined); // Returns true, as undefined cannot be
converted to a valid number
isNaN(456); // Returns false, as 456 is a valid numeric value
isNaN(true); // Returns false, as true is converted to 1, a valid
number
isNaN(false); // Returns false, as false is converted to 0, a valid
number

isNaN(null); // Returns false, as null is converted to 0, a valid


number
EASY
Q.8 Is javascript a statically typed or a
dynamically typed language?
JavaScript is a dynamically typed language. In a dynamically typed
language, variable types are determined at runtime, allowing a
variable to hold values of any type without explicit type declarations.
This flexibility can make coding more convenient but may also lead to
runtime errors if types are not handled appropriately.

JavaScript, being dynamically typed, allows variables to change types


during execution and accommodates a wide range of data types
without explicit type annotations.
MEDIUM
Q.9 What is NaN?
 Functions that treat other functions as values, either by:
25 Taking one or more functions as arguments&
+5 Returning a function as a result
Common Examples of Built-in HOFs:
TR map():
x Applies a function to each element of an array and creates a new
array with the results.&
x Example:

const numbers = [1, 2, 3, 4, 5]; 

const doubledNumbers = numbers.map(number => number * 2); //
[2, 4, 6, 8, 10]
“R filter():
x Creates a new array containing only elements that pass a test
implemented by a provided function.&
x Example: 

const numbers = [1, 2, 3, 4, 5]; 

const evenNumbers = numbers.filter(number => number % 2 ===
0); // [2, 4]
MEDIUM
 reduce():
. Applies a function against an accumulator and each element in an
array (from left to right) to reduce it to a single value.
. Example: 

const numbers = [1, 2, 3, 4]; 

const sum = numbers.reduce((accumulator, number) =>
accumulator + number, 0); // 10
Creating Custom HOFs:
You can define your own HOFs to encapsulate common patterns and
operations:

Javascript

function createMultiplier(factor) {

return number => number * factor;

const triple = createMultiplier(3);

const tripledNumbers = numbers.map(triple); // [3, 6, 9, 12, 15]


EASY
Q.10 What is difference between Null and
Undefined
Feature Null Undefined

Type Object Undefined

Definition Assignment value Variable declared but not


indicating no object yet assigned a value

Nature Primitive value Primitive value used when


representing null/empty a variable is unassigned

Representat Absence of a value for a Indicates the absence of


ion variable the variable itself

Conversion in Converted to zero (0) Converted to NaN during


Operations primitive operations
MEDIUM

Q.11 What is DOM?

DOM stands for Document Object Model, serving as a


programming interface for web documents.
vp Tree Structure: It represents the document as a tree, with the
document object at the top and elements, attributes, and text
forming the branches.\
Jp Objects: Every document component (element, attribute, text) is
an object in the DOM, allowing dynamic manipulation through
programming languages like JavaScript.\
Sp Dynamic Interaction: Enables real-time updates and interactions
on web pages by modifying content and structure in response to
user actions.\
Qp Programming Interface: Provides a standardized way to interact
with a web document, accessible and modifiable using scripts.\
Kp Cross-platform and Language-Agnostic: Not bound to a specific
language and works across various web browsers, ensuring a
consistent approach to document manipulation.\
+p Browser Implementation: While browsers have their own DOM
implementations, they follow standards set by the World Wide Web
Consortium (W3C), ensuring uniformity in document
representation and manipulation.
MEDIUM
Q.12 What is BOM?

BOM (Browser Object Model) is a programming interface


extending beyond DOM, providing control over browser-related
features.
T{ Window Object: Core BOM element representing the browser
window, with properties and methods for browser control.b
C{ Navigator, Location, History, Screen Objects: Components
handling browser information, URL navigation, session history, and
screen details.b
;{ Document Object: Accessible through BOM, allowing interaction
with the structure of web pages.b
r{ Timers: Functions like setTimeout and setInterval for scheduling
code execution.b
0{ Client Object: Represents user device information, aiding in
responsive web design.b
/{ Event Object: Manages events triggered by user actions or
browser events.
MEDIUM
Q.13 Explain about this keyword in
Javascript with an example.
In JavaScript, the this keyword is a special variable that is
automatically defined in the scope of every function. Its value
depends on how the function is invoked. The this keyword is used to
refer to the object that is the current context of the function or, more
simply, the object that the function is a method of.

Here are some common scenarios that affect the value of this:
Global Context:
When this is used outside of any function or method, it refers to the
global object (in a browser environment, it usually refers to window).
Javascript
console.log(this); // refers to the global object
(e.g., window in a browser)

Method Invocation:
When a function is a method of an object, this refers to that object.
MEDIUM
Javascript

const myObject = {

myMethod: function() {

console.log(this); // refers to myObject

};

myObject.myMethod();

Constructor Function:
When a function is used as a constructor with the new keyword, this
refers to the newly created instance of the object.
Javascript

function MyClass() {

this.property = 'some value';

const myInstance = new MyClass();

console.log(myInstance.property); // 'some value'


MEDIUM
Q.14 What is scope in Javascript?
In JavaScript, the term "scope" refers to the context in which
variables and functions are declared and accessed. It defines the
visibility and accessibility of these variables and functions within the
code. Understanding scope is crucial for managing the lifecycle and
behaviour of variables and functions in a program.

There are two main types of scope in JavaScript: global scope and
local scope.
Global Scope:
[ Variables declared outside of any function or block have global
scope.E
[ Global variables are accessible throughout the entire code,
including within functions.
Javascript
var globalVar = "I am global";

function exampleFunction() {

console.log(globalVar); // Accessible inside the


function

exampleFunction();

console.log(globalVar); // Accessible outside the


function
MEDIUM
Local Scope:
# Variables declared inside a function or block have local scope.
# Local variables are only accessible within the function or block
where they are declared.
Javascript

function exampleFunction() {

var localVar = "I am local";

console.log(localVar); // Accessible inside the


function

exampleFunction();

// console.log(localVar); // This would result in an


error because localVar is not accessible outside the
function

Scope Chain:
The scope chain refers to the hierarchy of scopes in a program. When
a variable or function is referenced, JavaScript looks for it in the
current scope and then traverses up the scope chain until it finds the
variable or reaches the global scope.
MEDIUM
Javascript

var globalVar = 42;

function mainFunction(){

var localVar1 = 777;

var innerFunction1 = function(){

console.log(localVar1); // Accesses localVar1 inside


innerFunction1, outputs 777

var innerFunction2 = function(){

console.log(globalVar); // Accesses globalVar inside


innerFunction2, outputs 42

innerFunction1();

innerFunction2();

mainFunction();
MEDIUM

Q.15 What is closure in Javascript?

In JavaScript, a closure is a function along with its lexical scope,


which allows it to access variables from its outer (enclosing) scope
even after that scope has finished executing. A closure allows a
function to remember and access variables from the environment in
which it was created, even if the function is executed in a different
scope.

Here's an example to illustrate closures in JavaScript:


MEDIUM
Javascript

function outerFunction() {

// Outer function scope

let outerVariable = 10;

function innerFunction() {

// Inner function scope

let innerVariable = 5;

// Accessing both inner and outer variables

console.log("Inner Variable:", innerVariable);

console.log("Outer Variable:", outerVariable);

// Returning the inner function, creating a closure

return innerFunction;

// Calling outerFunction returns innerFunction,


which is now a closure

let closureFunction = outerFunction();

// Executing the closure function

closureFunction();
MEDIUM
outerFunction defines an outer variable (outerVariable) and an
inner function (innerFunction).

innerFunction has access to the variables of its outer function


(outerVariable).

outerFunction returns innerFunction, creating a closure.

The returned closureFunction retains access to the


outerVariable even after outerFunction has finished executing.

Calling closureFunction() logs both the inner and outer variables


to the console.
HARD
Q.16 Explain call(), apply() and bind()
methods in Javascript.
In JavaScript, the call, apply, and bind methods are used to
manipulate how a function is invoked and set the value of this within
the function.
call method:
The call method is used to invoke a function with a specified this
value and arguments provided individually.
Javascript
function sayHello(greeting) {

console.log(greeting + ' ' + this.name);

const person = { name: 'John' };

sayHello.call(person, 'Hello'); // Outputs: Hello


John

Here, call is used to invoke the sayHello function with person as


the this value, and 'Hello' as an argument.
HARD
apply method:
The apply method is similar to call, but it accepts arguments as an
array.
Javascript

function sayHello(greeting) {

console.log(greeting + ' ' + this.name);

const person = { name: 'John' };

sayHello.apply(person, ['Hello']); // Outputs: Hello


John

In this example, apply is used to achieve the same result as call,


but the arguments are provided as an array.
bind method:
The bind method creates a new function with a specified this value
and, optionally, initial arguments.
HARD
Javascript

function sayHello(greeting) {

console.log(greeting + ' ' + this.name);

const person = { name: 'John' };

const sayHelloToJohn = sayHello.bind(person);

sayHelloToJohn('Hello'); // Outputs: Hello John

Here, bind is used to create a new function (sayHelloToJohn)


where this is permanently set to person. When calling
sayHelloToJohn, it's as if you're calling sayHello with person as
this.

These methods are especially useful when dealing with functions that
are part of objects or classes, and you want to explicitly set the
context (this) for their execution.
MEDIUM
Q.17
Explain call(), apply() and bind()
methods in Javascript.
In JavaScript, the call, apply, and bind methods are used to
manipulate how a function is invoked and set the value of this within
the function.
call method:
The call method is used to invoke a function with a specified this
value and arguments provided individually.
Javascript

function sayHello(greeting) {

console.log(greeting + ' ' + this.name);

const person = { name: 'John' };

sayHello.call(person, 'Hello'); // Outputs: Hello


John

Here, call is used to invoke the sayHello function with person as


the this value, and 'Hello' as an argument.
MEDIUM
In this example, the add function is pure because it only depends on
its input parameters (a and b) to produce a result and doesn't modify
any external state.

Contrast this with an impure function that relies on external state or


has side effects:

Javascript

// Impure function (has side effects)

let total = 0;

function addToTotal(value) {

total += value;

// Example usage of the impure function

addToTotal(5);

console.log(total); // Output: 5

In this case, addToTotal is impure because it modifies the external


variable total and has a side effect that can affect other parts of the
program.
MEDIUM
Q.18 What are prototypes in Javascript?
* Every object in JavaScript has a prototype, which acts as a
blueprint for shared properties and methods.7
* When you try to access a property or method on an object,
JavaScript first checks the object itself.7
* If it's not found, it looks up the prototype chain, following a linked
list of prototypes until it finds what it's looking for, or reaches the
end (null).
Example:
Javascript
function Person(name) {

this.name = name;

// Add a method to the prototype, shared by all


Person objects:

Person.prototype.greet = function() {

console.log("Hello, my name is " + this.name);

};
MEDIUM
Javascript

// Create two Person objects:

const person1 = new Person("Alice");

const person2 = new Person("Bob");

// Both objects can access the greet method from the


prototype:

person1.greet(); // Output: "Hello, my name is


Alice"

person2.greet(); // Output: "Hello, my name is Bob"

The Person function acts as a constructor to create objects with a


name property.

The greet method is added to the Person.prototype, meaning it's


shared by all instances created from Person.

When person1.greet() is called, JavaScript finds the greet method on


the prototype, so it can be used even though it wasn't defined
directly on person1.
HARD
What are callback functions in
Q.19
Javascript and what is callback hell?
In JavaScript, a callback is a function that is passed as an argument
to another function and is executed after the completion of some
asynchronous operation or at a specified time. Callbacks are
commonly used in scenarios like handling asynchronous tasks, event
handling, and other situations where the order of execution is not
guaranteed.

Javascript

function customGreeting(name) {

console.log("Welcome, " + name + "! How can we


assist you today?");

function outerFunction(callback) {

let name = prompt("Please enter your name.");

callback(name);

outerFunction(customGreeting);

In this example, the customGreeting function is the callback


function passed to outerFunction
HARD
Callback hell (or "pyramid of doom") is a situation in which multiple
nested callbacks make the code difficult to read and maintain. This
often occurs when dealing with asynchronous operations, such as
making multiple API calls or handling multiple events.

Here's an example of callback hell:

Javascript

getUser(function(user) {

getProfile(user.id, function(profile) {

getPosts(user.id, function(posts) {

displayUserProfile(user, profile, posts,


function() {

// More nested callbacks...

});

});

});

});

In this example, we have nested callbacks for getting a user, fetching


their profile, retrieving their posts, and finally displaying the user
profile. As more asynchronous operations are added, the code
becomes more difficult to read and maintain.

To address callback hell, developers often use techniques like


Promises or async/await in modern JavaScript to make code more
readable and manageable.

MEDIUM
Q.20 What is Temporal Dead Zone in
Javascript?
The Temporal Dead Zone is a phenomenon in JavaScript associated
with the use of the let and const keywords, unlike the var keyword. In
ECMAScript 6, attempting to access a let or const variable before it is
declared within its scope results in a ReferenceError. The term
"temporal dead zone" refers to the timeframe during which this
occurs, spanning from the creation of the variable's binding to its
actual declaration.

Let's illustrate this behaviour with an example:


Javascript
function exampleMethod() {

console.log(value1); // Outputs: undefined

console.log(value2); // Throws a ReferenceError

var value1 = 1;

let value2 = 2;

In this example, attempting to access value2 before its declaration


causes a ReferenceError due to the temporal dead zone, while
accessing value1 results in an output of undefined.
HARD
Q.21 What are promises in Javascript?

JavaScript Promises offer a streamlined approach to managing


asynchronous operations, mitigating the callback hell problem
encountered with events and traditional callback functions. Before
Promises, working with callbacks often led to code that was hard to
manage due to nested structures. Promises serve as a cleaner
solution for handling asynchronous tasks in JavaScript.

Here's the syntax for creating a Promise:

Javascript

let promise = new Promise(function(resolve, reject)


{

// Perform asynchronous operations

});

The Promise constructor takes a single callback function as its


argument, which, in turn, accepts two parameters: resolve and
reject. The operations inside this callback determine whether the
Promise is fulfilled by calling resolve or rejected by calling reject.

A Promise can exist in one of four states:


Å fulfilled: The action related to the promise succeeded.¾
Å rejected: The action related to the promise failed.¾
Å pending: The promise is still awaiting fulfilment or rejection.¾
Å settled: The promise has been either fulfilled or rejected.
MEDIUM
Q.22 Explain rest parameter in Javascript

In JavaScript, the rest parameter is a feature that allows you to


represent an indefinite number of arguments as an array. It is denoted
by three dots (...) followed by the parameter name. The rest
parameter collects all the remaining arguments passed to a function
into a single array.

Here's a simple example to illustrate the concept:


Javascript
function sum(...numbers) {

return numbers.reduce((total, num) => total + num,


0);

console.log(sum(1, 2, 3, 4, 5)); // Output: 15

In this example, the sum function accepts any number of arguments.


The rest parameter ...numbers collects all the arguments into an array
called numbers. The function then uses the reduce method to sum
up all the numbers in the array.

It's important to note that the rest parameter must be the last
parameter in the function declaration. For example, this is valid:
MEDIUM
Javascript

function example(firstParam, ...restParams) {

// code here

But this is not:


Javascript

function invalidExample(...restParams, lastParam) {

// code here

}
HARD
Q.23 What are generator functions in
Javascript?
In JavaScript, generator functions are a special kind of function that
allows you to control the execution flow and pause/resume it at
certain points. Generator functions are defined using the function*
syntax and use the yield keyword to produce a sequence of values.
When a generator function is called, it returns an iterator called a
generator.

Here's a simple example of a generator function:


Javascript
function* simpleGenerator() {

yield 1;

yield 2;

yield 3;

} // Creating a generator

const generator = simpleGenerator();

// Using the generator to get values

console.log(generator.next()); // { value: 1, done:


false }

console.log(generator.next()); // { value: 2, done:


false }

console.log(generator.next()); // { value: 3, done:


false }
HARD
console.log(generator.next()); // { value: undefined,
done: true }

In this example:
O The function* simpleGenerator() syntax defines a generator
function.@
O The yield keyword is used to produce values. Each time yield is
encountered, the generator pauses its execution, and the yielded
value is returned to the caller along with done: false. The
generator can be resumed later.@
O The generator.next() method is used to advance the
generator's execution. It returns an object with two properties:
value (the yielded value) and done (a boolean indicating whether
the generator has finished).

Generators are useful for lazy evaluation, asynchronous programming,


and creating iterable sequences.
MEDIUM
Q.24 What is the difference between function
declarations and function expressions?
Function Declaration:
C A function declaration is a statement that defines a function and
hoists it to the top of the current scope.3
C It starts with the function keyword, followed by the function
name, parameters (enclosed in parentheses), and the function
body.3
C Example:
Javascript
function add(a, b) {

return a + b;

Function declarations can be called before they are declared in the


code because of hoisting.
Function Expression:
C A function expression is an assignment where a function is defined
as part of an expression.3
C It does not get hoisted in the same way as function declarations.
MEDIUM

 Example:

Javascript

var add = function(a, b) {

return a + b;

};

In this example, add is a variable that holds an anonymous function.

Function declarations are hoisted, while function expressions are not

hoisted in the same way. If you try to call a function expression before

its definition, you'll get an error.

Function expressions are often used in cases where you need to

assign a function to a variable or pass it as an argument to another

function.
HARD
What is the difference between setTimeout,
Q.25 setImmediate and process.nextTick?

setTimeout, setImmediate, and process.nextTick are all functions in


Node.js that allow you to schedule the execution of a callback
function, but they have some differences in terms of when the
callback will be executed.
EC setTimeout:
` Schedules the callback to be executed after a specified delay (in
milliseconds).Z
` The callback is added to the event queue, and it will be executed
after the specified delay, but the exact timing is not guaranteed.
Javascript
setTimeout(() => {

console.log('This will be executed after 1000


milliseconds');

}, 1000);

™C setImmediate:
` Schedules the callback to be executed in the next iteration of the
event loop.Z
` It's often used when you want the callback to be executed
immediately after the current event loop cycle.
HARD
Javascript

setImmediate(() => {

console.log('This will be executed in the next


iteration of the event loop');

});

:3 process.nextTick:
O Executes the callback after the current event loop cycle, but
before the event loop continues processing other I/O events.L
O It is often used when you want to execute a callback after the
current operation but before I/O events.
Javascript

process.nextTick(() => {

console.log('This will be executed in the next


event loop cycle');

});
Why

Bosscoder?
750+ Alumni placed at Top
Product-based companies.

More than 136% hike for every 



2 out of 3 working professional.

Average package of 24LPA.

Explore More
Introduction
Hey there! Thank you for downloading the e-book. It’s designed to
help you prepare for a technical interview in JavaScript.

JavaScript is tricky and interviewers love to post questions that test the
depth of your knowledge.

This e-book is a compilation of the short articles that I write at


learn.coderslang.com. I have included only the ones tagged js-test ,
but there’s a lot more, so you might want to explore it further for more
programming tutorials.

Here’s what you’ll find in it:

35 colorful JS code snippets


Detailed explanation to every problem
A surprise on the last page :)

The blank space on the pages with code snippets was left there
itentionally. Before looking up the correct answer and an explanation,
you should spend a couple of minutes thinking about all the corner
cases.

If you’re looking to learn from scratch, this e-book won’t be very


helpful. It’s written specifically for those who are struggling to land
their first or maybe a second job in IT.

But don’t despair, as I have a Full Stack JS course that you can start
even without any prior knowledge.
JS Test #1: Type conversion in
JavaScript

What's going to be printed to the console?


In the first line, we define the variable str and initialize it as a string
with the value 1 .

In the second line, there are two typecasts, first !str gives us false
and then +false converts boolean into a number 0 .

Eventually, in the third line, the typeof operator looks up the current
type of str which is number .

ANSWER: string number will be printed to the console


JS Test #2: How to create an array in
JavaScript

What's the correct way to create an array in JS?


The first array, a1 is declared using an empty array literal. There are
no issues with it. In fact, it’s one of the most common ways of
declaring an array in JS.

The second one, a2 is created by calling Array as a function. It’s fine


and it creates an empty array as well.

The third array, a3 is created using an explicit call to the Array


constructor as we use the new keyword there.

ANSWER: All arrays are created correctly


JS Test #3: Adding strings to numbers
and booleans

Will we see any output? If yes, then what would it be?


To answer this question correctly, you need to understand the
typecast rules in JS.

The arithmetic operations + and - have the same priority, so the


value of x will be calculated from left to right without any exceptions.

First, we concatenate the string '2' with the number 3 . The result is
the string '23' .

Second, we try to subtract the boolean value true from the string
'23' . To make this operation possible, both boolean and a string have
to be cast to a number. Non-surprisingly '23' becomes 23 and true
is turned to 1 . Eventually, we do the subtraction and get the result,
number 22 .

The last step is to add the string '1' to the number 22 . Applying the
same concatenation that we did on the first step gives us the result - a
string '221' .

ANSWER: there are no issues with the expression in line 1. The value
of x is a string ’221’ , which will be successfully logged to the screen.
JS Test #4: try/catch

How will the try/catch blocks behave? What will be logged to the
console?
So, we have 2 variables and 2 try/catch blocks that supposedly catch
errors and put them into e1 and e2 .

Then, the content of errors is analyzed, compared and the comparison


result is logged to the screen.

First, let’s determine what’s inside of e1 and e2 . To do that, we need


to check the code in the try blocks. Both trying to get to null.length
and undefined.length will throw an error as neither undefined nor
null have the length property.

These errors will be caught in the catch blocks as e and then assigned
to the variables e1 and e2 .

The content of these errors will be a bit different. If we were to log


e.message to the screen in the catch block, we would see the
following:

Cannot read property 'length' of null


Cannot read property 'length' of undefined

Then, .split(' ')[0] gives us the first words of these sentences


which is Cannot in both cases. So ultimately, the program can be
simplified to:

console.log('Cannot' === 'Cannot')

ANSWER: the expression in the console.log will be evaluated as


true and logged to the screen.
JS Test #5: Can you use an arrow
function as a getter?"

Are there any issues with the getId function? What will be logged to
the screen?
So, getId is an arrow function, thus it doesn’t have this of its own.

It’s not bound to this of the obj object and when we try to get
this.id it will be evaluated to undefined and not 1 .

ANSWER: undefined will be logged to the console.


JS Test #6: Variable number of
arguments in JavaScript

true or false ? That is the question...


In JS, all functions have access to the internal arguments array that
holds all arguments that were passed into the function.

We can access the elements of this array by index, thus expecting that
both regularFunction and arrowFunction will return true.

The only issue is that arrow functions don’t have access to the
arguments array.

There might be two separate outcomes in line 8. Most likely you’ll see
the message ReferenceError: arguments is not defined . However,
there also might be a different scenario. For example, if you run this
code in Node.js, arguments[2] is likely to be evaluated to something
like

Module {
id: '.',
path: '/workdir_path',
exports: {},
parent: null,
filename: '/workdir_path/scriptName.js',
loaded: false,
children: [],
paths: [
'/node_modules'
]
}

In which case, we’ll see false logged to the screen as 3 is not equal to
the object described above.

ANSWER: false or ReferenceError will appear in the console


depending on the execution environment
JS Test #7: Is this an array?

Let's find out what’s the deal with JavaScript arrays. Is array an array?
In line one we create an array and bind it with the array constant.
Then the type of the value of this constant is evaluated by the typeof
operator.

There’s no such type as array in JS, so it’s impossible to see the


message ARRAY! on the screen. In fact, all JS arrays are objects, so the
execution goes into the else branch, and SOMETHING WEIRD is printed
on the screen.

ANSWER: SOMETHING WEIRD will be logged to the screen as all JS arrays


have the type object .
JS Test #8: Zero timeout

What if we call setTimeout with 0 delay in JavaScript? Which of the


messages will be printed first?
In JS, setTimeout(func, delay) takes a function func and delays its
execution by delay milliseconds.

It may seem that if we set the delay to 0 , then the function will be
executed immediately, but it’s not the case.

The function will be placed in the message queue to run


asynchronously. This will happen only after the current synchronous
execution is done.

The console.log in the second line is a part of the synchronous


execution and will run before the console.log in the first line.

In most web browsers setTimeout(f, 0) has a delay of


approximately 3 ms which is determined by the speed of internal
processing.

ANSWER: The message plain log will be printed first and then the
message timeout log will follow.
JS Test #9: Promise.reject + try/catch

Let's try to reject the promise inside of the JS try/catch . Will we catch
the error in the catch block?
Regular try/catch blocks only catch errors that appear in the
synchronous code.

As the Promise in the second line doesn’t have its own asynchronous
.catch block, the rejection will be left unhandled.

An UnhandledPromiseRejectionWarning will be raised and the code


inside of the regular catch block will not be executed.

ANSWER: The error will not be caught and the message the error
was caught! will NOT be logged to the console.
JS Test #10: null + undefined

What's the difference between null and undefined in JavaScript?


What will be logged to the console?
In the first line, we evaluate null === null and the result is true .

In the second line, we evaluate undefined === undefined and the


result is true once again.

In the third line, however, we need to understand what the result of


null + undefined is. For JavaScript, it’s hard to make sense of what it
should be, so it evaluates this expression as NaN .

Now, is NaN equal to NaN ?

And the answer is - NO.

In JS NaN is the only value that’s not equal to itself.

ANSWER: The output is going to be true , true , and false .


JS Test #11: Scope

Variables with the same name in JavaScript? What will be logged to the
console?
In the first line, we see an array animals that holds 5 strings.

The length of this array is used in the loop condition, so the loop will
continue spinning up to the point when i becomes equal to 5 .

Inside of the loop, a new array is declared with the same name
animals . There are no issues with such a declaration and no errors
will be thrown.

It’s important to remember, though, that the value animals.length in


the loop condition is attributed to the external array with 5 elements
but the console.log picks up the inner array, which has only 2
elements in it.

Once we go out of bounds there will be no error like in C++ or Java .


Instead, we’ll get undefined as the result of the last 3 iterations of the
loop.

ANSWER: The strings Whale , Dolphin will be logged to the console,


followed by undefined , undefined , undefined .
JS Test #12: Math.min()

How small is Math.min() in JavaScript?


The function Math.min() takes the variable number of arguments and
returns the lowest number passed into it.

In our case, it’s called without any arguments which is a special case.

If Math.min() is called without any parameters, it will return Infinity


which is the opposite of what you might have expected.

ANSWER: true will be printed to the screen as Infinity is greater


than 0 .
JS Test #13: Big number

We're just logging a number, what can go wrong here?


Under the hood, there are no integers in JavaScript.

All numbers are represented as 64-bit floats. This is also known as


double precision .

52 bits are used to store digits, 11 bits serve to track the position
of the decimal point, and 1 bit holds the sign and determines
whether the number is positive or negative.

When there’s not enough "space" to store the whole number, then
rounding to the nearest possible integer occurs.

It’s impossible to store the number 9999999999999999 using 52 bits ,


so the rounding gets rid of the least significant digits which leads to
the result of 10000000000000000 .

In JavaScript, no error will be thrown in this case.

If you haven’t quite understood what’s going on here, make sure to


read the lecture on Binary Number System of my Full Stack JS course
CoderslangJS.

ANSWER: 10000000000000000 will be printed to the screen.


JS Test #14: 0.1 + 0.2 = ?

JavaScript math is weird. What’s the output? True or false?


Inside the computer, all numbers are stored in the Binary Number
System.

To keep it simple, it’s the sequence of bits - which are "digits" that
can be either 0 or 1 .

The number 0.1 is the same as 1/10 which can be easily represented
as a decimal number. In binary, it will result in an endless fraction,
similar to what 1/3 is in decimal.

All numbers in JavaScript are stored as 64-bit signed floating-point


values, and when there’s not enough space to hold the value, the least
significant digits are rounded.

This leads us to the fact that in JavaScript 0.1 + 0.2 render


0.30000000000000004 and not 0.3 like you would have obviously
though.

There's a whole lecture dedicated to the Binary Number System in


my Full Stack JS course CoderslangJS.

ANSWER: false will be printed on the screen.


JS Test #15: Getter function

Can we use an arrow function as a getter in JavaScript? What's going


on and what will be logged to the console?
So, we have an object with a single field id equal to 1 and two
functions getIdArrow and getIdFunction which supposedly do the
same thing, return the value of id .

Unfortunately, that’s not the case. In JavaScript, arrow functions are


different from the regular ones. There’s no binding between this
inside of the arrow function and the object obj . Thus this.id will be
evaluated to undefined .

In case of the getIdFunction , this is bound to the obj and this.id


is the same as obj.id , which is 1 .

ANSWER: the first console.log will print the number 1 to the


console. The second one will print false .
JS Test #16: typeof NaN

What's the type of Not a Number ?


In JavaScript, NaN means Not a Number . This is a special value that
appears whenever JS can’t make sense of the numerical expression.

NaN also often appears during typecast. For example, if you try to
convert the string into a number, the result will be NaN .

It may seem counterintuitive, but NaN is just a special number. Thus its
type is considered to be number .

You can tackle this problem from a different angle and try to answer
the question:

What else typeof NaN can be?

ANSWER: the typeof NaN is number , which will be logged to the


console.
JS Test #17: Sum of two empty arrays
in JavaScript

Is the sum of two arrays equal to false ?


To analyze this code snippet we need to understand how type
conversion works in JS.

When we try to sum two arrays using the + operator, the arrays are
first converted to strings and then these strings are concatenated.

An empty array [] is evaluated as an empty string. The sum of two


empty strings is still an empty string.

Now, is an empty string equal to false or not?

The comparison here is done using the == operator. This operator is


used to check loose equality and does implicit type conversion.

In this case, empty string and false are considered equal and the
condition of the if statement will be evaluated to true .

If you want to use a strict comparison which respects the types of


values you compare, you should use the strict equality operator === .

Here, you can find more information on basic math operations is


JavaScript.

ANSWER: the string same will be logged to the console.


JS Test #18: What's the sum of two
booleans in JavaScript?

Can you add booleans in JS? Is something false here? What will be
logged to the screen?
Just as in the previous test, we’re dealing here with type conversion
and loose equality using the == operator.

When JavaScript evaluates the expression true + true it first


converts booleans to numbers, which is 1 for true and 0 for false .

When we try to do calculate the value of 2 == true , the typecast


happens again and we arrive at the final condition 2 == 1 .

The result is obviously false, so we go into the else branch.

To understand how type conversion works with the + operator and


different data types, you can read this article.

ANSWER: the string everyone is different after all will be logged


to the console.
JS Test #19: Catching the rejected
Promise

Can you catch the Promise rejection in JS? Another unhandled


rejection?
In JS, it’s impossible to catch the unhandled promise rejection using
the regular try/catch blocks.

So, if the rejection does take place, then we’ll likely see a message like
UnhandledPromiseRejectionWarning … or something along these
lines.

Here, though, we don’t get to reject the promise properly.

JavaScript tries to evaluate the result of null.length which happens


synchronously. An error Cannot read property 'length' of null
will be thrown and caught in the catch block.

ANSWER: the error will be caught and the string the error was
caught! Cannot read property 'length' of null will be logged to
the screen.
JS Test #20: Can you sum arrays with
objects in JavaScript?

What’s the sum of an empty object and an empty array in JS? Is there
any length to be found?
Once again, we’re dealing with type conversion in JavaScript.

Both an empty array and an empty object will be converted to strings.

In the case of an empty array, it will be an empty string.

But for the empty object, we get the string [object Object] !

The length of this string is greater than 10, so we’ll see the first
message logged to the console.

More examples of JavaScript typecast are covered here.

ANSWER: the string wow, this is quite long will appear on the
screen.
JS Test #21: ISO Date

How does the ISO date look in JavaScript? What will be logged to the
console?
In the first line, we create a new Date object.

It holds the current date and time.

The function toISOString returns the string representation of the


date object in the ISO format. It starts with the year and ends with
time. Something like 2020-12-27T10:35:26.159Z .

When we’re slicing this string with slice(0, 4) we’ll get the first four
characters, which represent the year.

ANSWER: the current year will be logged to the console.


JS Test #22: How toString works in
JavaScript?

Let's try to apply a generic toString function to a regular JavaScript


array. What’s the output?
In the first line, we’ve saved the function Object.prototype.toString
into the constant toString . This function is called whenever the
object has to be converted to a string.

Most objects provide an overridden implementation of the toString


function. For example, an array will look like a comma-separated list of
all values it holds.

The default behavior of Object.prototype.toString is to return a


string of the format [object "TYPE"] . The "TYPE" is substituted with
the actual type of the object. In our case, it’s Array .

So, with toString.call(arr) we call the original implementation of


Object.prototype.toString .

ANSWER: the string [object Array] will be printed to the console.


JS Test #23: Array.splice"

How many times can you splice the array in JavaScript?


Let’s start with the definition of splice .

The function splice is available in all JavaScript arrays and accepts


the variable number of parameters. Here are 4 important things you
should know about splice :

The first parameter is called start and represents the index of the
first element that will be removed from the array.
The second argument is deleteCount . It determines the number
of array elements that will be removed from the array
The third, the fourth argument, and so on, are the new elements
that will be added to the array.
The function splice returns the array formed by deleted
elements.

Now, we start the array arr with 5 elements [1, 2, 3, 4, 5] .

The first splice extracts 2 elements starting from arr[1] . We


immediately save them into the splicedArr .

Before the final splice we have the following state:

[ 1, 4, 5 ] // arr
[ 2, 3 ] // splicedArr

The second splice once again removes 2 elements from arr starting
at arr[1] . This leaves us with a single element — 1 .

Then, we apply the destructuring with ... to the splicedArr and add
elements 2 and 3 to the initial array arr .

Here’s the code snippet with 2 additional calls to console.log to help


you understand the explanation better:
const arr = [1, 2, 3, 4, 5];
const splicedArr = arr.splice(1, 2);

console.log(arr); // [ 1, 4, 5 ]
console.log(splicedArr); // [ 2, 3 ]

arr.splice(1, 2, ...splicedArr);
console.log(arr);

ANSWER: the array will eventually hold values [ 1, 2, 3 ] which will


be logged to the console.
JS Test #24: Adding properties to
strings in JavaScript

Can you add a custom field to a regular JS string? What’s the output?
The answer to this problem will depend on whether you’ve added the
’use strict’ flag at the beginning of your script.

The result will be:

undefined if 'use strict' wasn’t specified


an error will be thrown if you’re using the strict mode

So what’s the deal?

In the second line, when you try to access s.user , JS creates the
wrapper object under the hood.

If you’re using the strict mode, any modification attempt will throw an
error.

If you’re not using the strict mode, then the execution will continue
and the new property user will be added to the wrapper object.

However, once we’re done with the second line of code, the wrapper
object is disposed and the user property is gone, so undefined is
logged to the console.

ANSWER: You can’t add properties to primitive values in JS. The result
will depend on the presence of the 'use strict' flag.
JS Test #25: Immediate
Promise.resolve

How fast is Promise.resolve() in JavaScript? Which of the messages


will be logged first?
The logic is almost the same as in this setTimeout example.

Even though Promise.resolve() doesn’t have any explicit delay, the


code inside of .then() is executed asynchronously and has a lower
priority than the synchronous code.

So, the console.log('resolved') will be executed after the


console.log('end') .

ANSWER: the string end will be logged first, followed up by resolved .


JS Test #26: Are these dates equal?

Are these dates equal?


In the first two lines we create new Date objects.

In line 4, we’re using the strict equality operator === . Remember that
we’re comparing different objects!

Even if date and date2 represented the same date, the check would
have returned false .

ANSWER: The string not so much will be printed to the console, as


date1 and date2 are different objects.
JS Test #27: Handling errors in
JavaScript Promise chains

Are there any differences between f1 and f2?


There are two ways of providing error handlers to the JavaScript
Promises.

The first one is shown in the function f1 . We pass the errorHandler


as a second argument to .then() .

The second approach is implemented in f2 . Here, we add the


errorHandler using the .catch() function.

In both cases errorHandler will be called if the original promise is


rejected.

If promise resolves successfully, then the execution continues in


successHandler . And if successHandler throws the error, then it will
only be handled by f2 and not f1 .

This happens because of the internal implementation of .catch() . It


handles all errors in the promise chain, including the ones inside of the
.then() handlers.

ANSWER: Yes, there’s a big difference between f1 and f2 . The former


doesn’t handle the error in successHandler (if it appears) and the
latter does.
JS Test #28: Resolve and reject at the
same time

Can you resolve and reject a Promise at the same time? What will be
printed to the console?
In JavaScript, promises can’t be resolved and rejected at the same
time.

The execution will never reach the call to setTimeout and thus
reject(2) , inside of it.

Thus only the number 1 will be printed on the screen.

ANSWER: A single message will be logged to the console. After the


promise is resolved with 1 the execution stops and the setTimeout
won’t be called.
JS Test #29: Slice and dice

What's happened to arr ?


Array.slice in JavaScript returns the shallow copy of the array. The
start and end indices should be supplied to it as the first 2
parameters. The element at arr[start] is included in the copy, and
the element at arr[end] is not.

Contrary to Array.splice , the original array won’t be modified when


we use Array.slice .

So, after the first 2 lines of code, we’ll get the following state:

[ 1, 2, 3, 4, 5] // arr
[ 2 ] // slicedArr

Then, we do two actions under arr.splice :

we remove 2 elements from arr starting at arr[1] . So the original


array becomes is [ 1, 4, 5 ] at this point.
we destructure …slicedArr and insert its elements into arr
starting at arr[1] . This way we’ll get to our final state [ 1, 2, 4,
5] in arr .

Here’s a code snippet with additional logging:

const arr = [1, 2, 3, 4, 5];


const slicedArr = arr.slice(1, 2);

console.log(arr); // [ 1, 2, 3, 4, 5]
console.log(slicedArr); // [ 2 ]

arr.splice(1, 2, ...slicedArr);
console.log(arr); // [ 1, 2, 4, 5]

ANSWER: The original array arr will be modified and hold values [ 1,
2, 4, 5] .
JS Test #30: Reject inside resolve

What will be logged to the console? Will the finally block be executed?
To analyze this code snippet, I'll start with the things that are clear:

the .then(console.log) function will not be executed and there’s


a rejection inside of the Promise.resolve()
the catch block won’t be able to catch the rejection as it happens
asynchronously

So, we’re left with the finally block. There’s a single call to the
console.log and it’s the first message the will be printed on the
screen.

Then, the unhandled rejection will happen as we haven’t provided the


error handler to the promise chain in line 2.

ANSWER: The string finally will be logged to the console followed by


the UnhandledPromiseRejectionWarning: -1 .
JS Test #31: Big or small

What's the output?


So, there’s an if statement and it’s condition Math.max() > 0 is all
we need to analyze.

If your first guess was that Math.max() should return some big
number that’s for sure bigger than 0 , then you’re wrong.

In JavaScript Math.max() takes a variable number of arguments and


returns the biggest one. The comparison starts at the very bottom,
which in JS is -Infinity because it’s smaller than all other numbers.

This is why if no arguments are provided to the Math.max() , it will


return -Infinity .

As -Infinity is smaller than 0 , we’ll go into the else branch of the


conditional statement.

ANSWER: string ZERO! will be logged to the console.


JS Test #32: 0.1 + 0.1 + 0.1 === 0.3

What will be logged to the console?


At a first glance, the answer is true as 0.1 + 0.1 + 0.1 is obviously
equal to 0.3 .

But that’s only before we get into the details of how the numbers are
represented in JavaScript.

If you try to execute the statement console.log(0.1 + 0.2) in JS,


you’ll get a number 0.30000000000000004 .

This happens because in JavaScript and quite a few other


programming languages some decimal numbers can't be represented
exactly as they are.

For example 0.1 in binary will result in an endless fraction, the same
way as 1/3 becomes 0.333(3) in the decimal number system.

ANSWER: false will be logged to the console.


JS Test #33: Add two empty arrays
and check the type

Array? Object? Undefined? What’s the output?


In JavaScript, the + operator doesn’t do the concatenation of arrays.

Instead, it transforms them into strings and then does the string
concatenation.

Two empty arrays become two empty strings, and their sum
unsurprisingly is still an empty string.

What matters to us is the typeof that will return string in our case.

ANSWER: the output will be string .


JS Test #34: Different ways to get
current date in JavaScript

How do you prefer to get the current date in JS? What will be logged to
the console?
Both new Date() and Date.now() in JavaScript return us the current
date and time.

The difference between them is that new Date() returns the Date
object and Date.now() returns the number of milliseconds elapsed
from the midnight of Jan 1, 1970.

If you need to compare two dates in different formats, you can always
get the number of milliseconds from any Date object using the built-in
getTime() function.

Otherwise, you won’t have any luck comparing a number to an object .

ANSWER: false will be logged to the console.


JS Test #35

What's the order of the output?


Both setTimeout and Promise.resolve are asynchronous actions,
which means that the inner console.log statements will be evaluated
after some delay.

The difference is that Promise.resolve schedules the microtask, and


setTimeout schedules the macrotask. Micro tasks have higher priority
than macrotasks, thus Promise.resolve will be evaluated faster and
the first output will be 2 .

ANSWER: 2 will be printed on the first line, followed by 1 .


Conclusion
Thank you for staying with me! I’m sure you’ve learned at least a
couple of new JS tricks to help you ace the next interview.

If some of the problems were not very clear to you, do go ahead and
visit learn.coderslang.com. There are multiple JavaScript articles and
tutorials to broaden your knowledge and make you a better dev.

Here are a couple of things you might want to consider next:

get the app Coderlslang on iOS or Android to prepare for the tech
interview not only in JS, but also in Java, Node, React, HTML, CSS,
QA, and C#
share this e-book with a friend or write a post about it
get more tests like these here

And last, but not least! I really appreciate your time reading this book,
so here’s a 15% discount code for my Full Stack JS course.

const DISCOUNT_CODE = 'surprise-js';

If you have any questions, feel free to find me on Twitter, Telegram or


just send a plain old email to welcome@coderslang.com
Index
Introduction .................................................................. 4
JavaScript Tips ............................................................... 5
Use proper variable names ......................................... 7
Be careful with comparison using the loose equality
operator ...................................................................... 8
Check property exists in an object .............................. 9
Conditionally add a property to an object ................ 10
Use includes to check for multiple criteria ............... 11
Remove duplicates from an array using Set ............. 12
Use spread operator to shallow copy arrays and
objects ...................................................................... 13
Avoid delete keyword ............................................... 14
Use Array.isArray to determine the array ................ 15
Use of falsy bouncer ................................................. 16
Use Array.some to check occurrence in array .......... 17
Readable numbers .................................................... 18
Pass function arguments as an object ...................... 19
Object destructuring on arrays ................................. 21
Skip values in array destructuring ............................ 22
Format the output of JSON.stringify ......................... 23
Filter with JSON.stringify .......................................... 24

1
Power of JSON.stringify replacer parameter ............ 25
Don’t extend built-ins ............................................... 26
Use of optional chaining on function call ................. 27
Convert to a flat array using Array.flat ..................... 28
Use console.time to debug performance ................. 29
Logging using console.group .................................... 30
Conditional log message using console.assert ......... 31
Display tabular data using console.table .................. 32
Default assignment for required arguments of the
function..................................................................... 33
Avoid default exports ............................................... 34
Use of object destructuring ...................................... 35
Lock an object using the Object.freeze..................... 36
Understanding of closures ........................................ 37
Smooth scroll to a specific element .......................... 38
Use Object.entries to access key and value .............. 39
Use of nullish coalescing operator with numbers .... 40
Use semicolons manually to avoid issues generated
by ASI ........................................................................ 41
Use of template literals with expressions and function
call............................................................................. 42
Use of template literals with variable substitutions
and multiline string ................................................... 43

2
Get an array of keys using Object.keys ..................... 44
Ways of a function declaration ................................. 45
Use of increment (++) and decrement (--) ................ 46
Property renaming in object destructuring .............. 47
Object nested destructuring ..................................... 48
Use id to find a single element ................................. 49
Use let instead of var for blocked statement ........... 50
Use of default parameters ........................................ 51
Add dynamic property to an object .......................... 52
Use curly brackets ({}) instead of new Object() ........ 53
Use square brackets ([]) instead of new Array() ....... 54
Declare common variables outside of the loop ........ 55
Create an object from key-value pairs using
Object.fromEntries ................................................... 56
Tests every element of the array using Array.every . 57
Read property using optional chaining (?.)............... 58
Easy way to swap two variables ............................... 59
Improve variable logging using console.log .............. 60
Mask numbers using slice and padStart ................... 61
String to a number using the plus (+) operator ........ 62

3
Introduction
For the last few months, I have been posting JavaScript
code snippets on LinkedIn, Instagram, and Twitter. This
book contains 51+ JavaScript code snippets that will
help you to improve your code.

Connect me.
LinkedIn: https://www.linkedin.com/in/manjurhusen/
Twitter: https://twitter.com/manjurhusen
Instagram:
https://www.instagram.com/manjur.momin/

4
JavaScript Tips

JavaScript is one of the most popular scripting or


programming language.

In 1995, Brendan Eich from Netscape designed and


implemented a new language for the Netscape
Navigator browser. It was initially named Mocha, then
LiveScript, and finally JavaScript.

JavaScript is everywhere.
• More than 94% of websites use JavaScript.
• JavaScript completes its ninth year in a row as the
most commonly used programming language.
(2021 StackOverflow developer survey)

I have used the following two images in some code


snippets with different meanings in different examples.
Image Meaning
Code is okay
Can improve code
Incorrect way

5
Better code
Improved code
Correct way

6
Use proper variable names

• Use the specific naming convention. Mostly used


camel-case naming convention.
• The variable name should be concise and
descriptive.
• It should explain the purpose.
• It is easy to pronounce.

7
Be careful with comparison using the loose
equality operator

Loose Equality Operator (== OR !=) performs the


automatic type conversion before comparison if
needed.
Like in the above example, you can get unexpected
output with Loose Equality Operator.

8
Check property exists in an object

The in operator returns the boolean value true/false.


The in operator returns true if a property exists in the
object or its prototype chain.

9
Conditionally add a property to an object

Use spread operator (...) to spread an object into


another object conditionally.
Use condition with && operator to add a new property
to an object. It will add a property to an object if the
condition match.

10
Use includes to check for multiple criteria

The includes() method determines whether an array


includes a certain value among its entries. It returns
true if a value exists, otherwise, it returns false.
Instead of extending the statement with more || (OR)
conditions, rewrite the conditional by using the
includes method.
More readable and concise alternative.

11
Remove duplicates from an array using Set

Set is a new data object introduced in ES6. The Set only


lets you store unique values of any type. When you
pass an array to a new Set(array), it will remove
duplicate values.
The spread syntax (...) is used to include all the items
of the Set to a new array.

12
Use spread operator to shallow copy arrays
and objects

Use the spread operator (...) to create a shallow copy


of the object and array.
The spread operator (...) allows us to make copies of
the original data (whether it is an array or object) and
create a new copy of it.
It is an easy and clean way.

13
Avoid delete keyword

Avoid a delete keyword to remove a property from an


object. This way mutates the original object and hence
leads to unpredictable behavior and makes debugging
difficult.
A better way to delete a property without mutating the
original object is by using the rest operator (...). Use
the rest operator (...) to create a new copy without the
given property name.

14
Use Array.isArray to determine the array

The Array.isArray() method determines if the given argument is an


Array or not.
• Returns true if the value is Array.
• Returns false if the value is not Array.

15
Use of falsy bouncer

A falsy value is a value that is considered false when


examined as a Boolean.
Falsy Bouncer means removing all falsy values from an
array.
Falsy values in JavaScript are false, null, 0, undefined,
NaN, and "" (empty string).
Pass the Boolean to Array.filter as the first argument
and it will serve as a falsy bouncer.

16
Use Array.some to check occurrence in array

If we want to check only occurrence means value exist


or not then use Array.some instead of Array.find.
The some() method checks if any array items pass a
test implemented by the provided function. If the
function returns true, some() returns true and stops.
The some() method does not change the original array.

17
Readable numbers

When working with large numbers it can be hard to


read them out.
The Numeric Separators allow us to use underscore (_)
as a separator in numeric literals, for example, you can
write 50000 as 50_000.
This feature improves readability.

18
Pass function arguments as an object

Parameters are part of a function definition. A


JavaScript function can have any number of
parameters. When we invoke a function and pass some
values to that function, these values are called function
arguments.
If a function has more than 1 parameter, it is hard to
figure out what these arguments mean when the
function is called. When you pass the arguments, the
order is important.
A better way is to create a function with object (with
properties) parameters like in the example. When we
pass the argument contained in an object it is pretty

19
much clear from the names of the properties. Also, the
order of properties doesn’t matter anymore.

20
Object destructuring on arrays

The destructuring assignment provides a clean way to


extract values from arrays and objects. Array
destructuring is a way that allows us to extract an
array’s value into new variables.
Each item in the array has an index. The property name
corresponds to the index of the item that returns the
value like in the example.
It is an easy way to get a specific item from an array in
a single line of code.

21
Skip values in array destructuring

Destructuring means breaking down a complex


structure into simpler parts.
Array destructuring is a way that allows us to extract
an array’s value into new variables. Sometimes we
don't need some values from the array means we want
to skip those values. During the destructuring arrays, if
you want to skip some values, use an empty
placeholder comma.
This is a clean way to skip values.

22
Format the output of JSON.stringify

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 3rd parameter to JSON.stringify() is called spacer.
You can pass String or Number value to insert
whitespace in the returned string.
If the 3rd parameter is a Number, it indicates the
number of spaces for indenting purposes.
If the 3rd parameter is a String, the string is used as
whitespace.

23
Filter with JSON.stringify

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 2nd parameter to JSON.stringify() is a replacer or
filter that can be a function or an array.
When 2nd parameter is passed as an array, it works as
a filter and includes only those properties in the JSON
string which are defined in an array.

24
Power of JSON.stringify replacer parameter

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 2nd parameter to JSON.stringify() is a replacer or
filter that can be a function or array.
When 2nd parameter is passed as a replacer function,
it alters the behavior of the stringification process. As a
function, it takes two parameters, the key and the
value being stringified.

25
Don’t extend built-ins

Extending built-in Objects/types or Array is not a good


practice in JavaScript.
A better way is to create your own utility library and
use it.

26
Use of optional chaining on function call

The optional chaining operator (?.) is a safe and


concise way to access properties that are potentially
null or undefined.
The chaining operator (.) throws an error if a reference
is null or undefined.
The optional chaining operator (?.) will return
undefined if a reference is null or undefined.
Just like with properties, we can use the optional
chaining operator with methods also.
Less code and clean way.

27
Convert to a flat array using Array.flat

Flattening an array is the process of reducing the


number of dimensions of an array to a lower number.
The flat() method creates a new array with all items of
subarray concatenated into it recursively up to the
specified depth.

28
Use console.time to debug performance

The console object has time() and timeEnd() methods.


These two methods help us to analyze the
performance of our code.
The console.time() method starts a timer to track how
long an operation takes. You can give each timer a
unique name. When you call console.timeEnd() with
the same name, the browser will output the time in
milliseconds.

29
Logging using console.group

The console object has group() and groupEnd()


methods.
The console.group() method starts a new inline group
in the web console log. This method takes an optional
argument label.
The console.groupEnd() method ends the group.
It organizes your messages and improves visibility.

30
Conditional log message using console.assert

The console object has an assert() method which helps


to log an error message conditionally.
The console.assert() method writes an error message
to the console if the assertion is false. If the assertion is
true, nothing happens.

31
Display tabular data using console.table

The console object has a table() method which allows


you to display arrays and objects to the console in
tabular form.
The console.table() method provides better data
visualization.

32
Default assignment for required arguments of
the function

You can use default parameters to make the function


arguments required.
If you don't provide the parameter, it will default to the
function which throws an error.
Note that null is considered a value, so passing null will
not result in a default assignment.

33
Avoid default exports

Problems with default exports are:


• Discoverability is very poor for default exports.
• Difficult to analyze by automated tools or provide
code autocompletion.
• Horrible experience for CommonJS.
• TypeScript auto-import struggles.
• Default exports make large-scale refactoring
impossible.

34
Use of object destructuring

Object destructuring provides a unique way to neatly


extract an object’s value into new variables.
To assign values to variables, declare the variables in
curly brackets and assign the object like in code
snippet.
To destructure into existing variables must surround
the variables with parentheses.

35
Lock an object using the Object.freeze

The Object.freeze() method freezes an object. A frozen


object can no longer be changed.
This method prevents new properties from being
added and modification of existing properties.

36
Understanding of closures

A closure is a mechanism that allows the inner function


to remember the outer scope variables when it was
defined, even after the outer function has returned.
The closure has three scope chains:
• It can access its own scope means variables
defined between its curly brackets ({ }).
• It can access the outer function’s variables.
• It can access the global variables.

37
Smooth scroll to a specific element

The Element.scrollIntoView() method scrolls the


specified element into the viewing portion of the
window.
It provides the behavior option for smooth scrolling.

38
Use Object.entries to access key and value

The Object.entries() method is used to return an array


of a given object's own enumerable property [key,
value] pairs.
The order of the properties is the same as in an object.

39
Use of nullish coalescing operator with
numbers

A Nullish value is a value that is either null or undefined.


The Nullish Coalescing Operator (??) is a logical operator that
accepts two values and returns the second value if the first one is
null or undefined and otherwise returns the first value.

40
Use semicolons manually to avoid issues
generated by ASI

ASI stands for Automatic Semicolon Insertion.


In JavaScript, semicolons are optional. JavaScript
Engine automatically inserts a semicolon, where it is
required.
If the code is not formatted correctly like in the above
example, JavaScript Engine will add a semicolon to the
end of the return statement and consider that no value
is returned. So, it returns as undefined.
You should not depend on the ASI. If ASI fails and you
are missing semicolons, the code will fail.

41
Use of template literals with expressions and
function call

Template Literals use back-ticks (``) instead of single


('') or double ("") quotes.
Template literals provide an easy way to interpolate
variables and expressions into strings.
Template literals allow expressions and functions in
strings.
Using template literal means not only less code but
higher readability also.

42
Use of template literals with variable
substitutions and multiline string

Template Literals use back-ticks (``) instead of single


('') or double ("") quotes.
Template literals provide an easy way to interpolate
variables and expressions into strings. You can do it
using the ${...} syntax.
Template literals make multiline strings much simpler.

43
Get an array of keys using Object.keys

The Object.keys() returns an array of a given object's


own enumerable property names.
The ordering of the properties is the same as that
when looping over them manually.

44
Ways of a function declaration

Functions are one of the fundamental building blocks


in JavaScript.
Following are the different ways to write functions.
• Function declaration
• Function Expression
• Arrow (=>) function
• Arrow (=>) function without curly braces ({}) – (Use
only for a single statement of code)

45
Use of increment (++) and decrement (--)

The increment operator (++) adds one (+1) to its


operand and returns a value. The increment (++)
operator can be used before or after the operand.
Increment Syntax: i++ or ++i
The decrement operator (--) subtracts one (-1) to its
operand and returns a value. The decrement (--)
operator can be used before or after the operand.
Decrement Syntax: i-- or --i

46
Property renaming in object destructuring

Object destructuring provides a unique way to neatly


extract an object’s value into new variables.
Sometimes an object contains some properties, but
you want to access it and rename it.
When renaming a variable in object destructuring, the
left-hand side will be the original field in the object, and
the right-hand side will be the name you provide to
rename it to.
It is also possible to destructure the same property
multiple times into different variable names like in
code snippet.

47
Object nested destructuring

With destructuring, we can quickly extract properties


or data from objects into separate variables.
You need to give a complete path when you have to
destructure a nested property.
Destructuring an object does not modify the original
object.

48
Use id to find a single element

Never use the same id for multiple elements on the


same HTML page.
The getElementById() method returns an element
object.
The getElementById() method returns null if the
element does not exist.
When you want to access any element, please use
element-id if exists. Access element by id is faster than
class.

49
Use let instead of var for blocked statement

Scope means where these variables are available for use. The var
declarations are globally scoped or function/locally scoped.
Using var is the oldest method of variable declaration in JavaScript. A
variable declared using var is function scoped when it is declared
within a function.
A let variable is scoped to the immediate enclosing block denoted by
curly braces ({ }). You cannot access the let variable outside of its
scope. The above code snippet shows the behavior of var and let
variable.

50
Use of default parameters

Default function parameters allow named parameters


to be initialized with default values if no value or
undefined is passed.
ES6 provides an easier way to set the default values for
the function parameters. Use the assignment operator
(=) and the default value after the parameter name to
set a default value for that parameter.

51
Add dynamic property to an object

ES6 provides an easy way to create a dynamic property


in an object.
We can simply pass the property name in square
brackets ([]) which we want to make property in the
object.

52
Use curly brackets ({}) instead of new Object()

Objects can be initialized using new Object(),


Object.create(), or using the literal notation.
You can use curly brackets ({}) to declare objects in
JavaScript. Creating a new object this way is called
object literal notation.
The advantage of the literal notation is, that you are
able to quickly create objects with properties inside the
curly brackets ({}). You notate a list of key: value pairs
delimited by commas.
Better and clean way.

53
Use square brackets ([]) instead of new Array()

Arrays can be created using the new Array(), but in the


same way, they can be created using literal notation
also.
You can use square brackets ([]) to declare arrays in
JavaScript. Creating an array this way is called array
literal notation.
The advantage of the array literal notation is, that you
are able to quickly create arrays.
Better and clean way.

54
Declare common variables outside of the loop

Variables that are not going to reassign in the loop


must be declared outside of the loop, otherwise, they
will be created again and assigned the same value
every time.

55
Create an object from key-value pairs using
Object.fromEntries

The Object.fromEntries() method transforms a list of


key-value pairs into an object.
Object.fromEntries() performs the reverse of
Object.entries().

56
Tests every element of the array using
Array.every

The Array every() method checks whether all the array


elements pass the test implemented by the provided
function.
It returns true if the function returns true for all
elements.
It returns false if the function returns false for one
element. When every() finds a false result, it will stop
the loop and continue no more which improves the
performance.
The every() method does not change the original array.

57
Read property using optional chaining (?.)

The optional chaining operator (?.) is a secure way to


read nested object properties, even if an intermediate
property doesn’t exist.
The optional chaining operator (?.) stops the
evaluation if the value before ?. is nullish (undefined or
null) and returns undefined.
It prevents writing boilerplate code.
Less and clean code.

58
Easy way to swap two variables

Use destructuring assignment approach because it is


short and expressive. Swapping is performed in just
one line statement. It works with any data type like
numbers, strings, booleans, or objects.

59
Improve variable logging using console.log

In JavaScript, we use console.log() to log the variables


or messages. Sometimes it is difficult to understand
what variable corresponds to a log in the console when
too many variable logs.
To log the variable, wrap the variable into a pair of
curly brackets {variable-name}.
It will improve readability.

60
Mask numbers using slice and padStart

The slice() method returns selected elements in an


array, as a new array. Negative numbers select from
the end of the array.
The padStart() method pads the current string with
another string until the resulting string reaches the
given length. The padding is applied from the start of
the current string.
Masking is possible with less code.

61
String to a number using the plus (+) operator

The unary plus operator (+) is the fastest and preferred


way of converting something into a number.

62
Quick JavaScript Interview Questions
Copyright Blurb
All rights reserved. No part of this book may be reproduced in any form or by any
electronic or mechanical means including information storage and retrieval systems –
except in the case of brief quotations in articles or reviews – without the permission in
writing from its publisher, Sandeep Kumar Patel.
All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. I am not associated with any
product or vendor in this book.
Published By
Sandeep Kumar Patel.
Table of Contents
Quick JavaScript Interview Questions Table of Contents
Chapter 1 Inheritance
Chapter 2 Questions on Event
Chapter 3 Closure
Chapter 5 Questions on DOM
Chapter 6 Date Object
Chapter 7 Regular Expression
Chapter 8 Questions on Canvas API Chapter 9 Geo Location API
Chapter 10 Web Workers
Chapter 11 Local Storage
Chapter 12 File API
Chapter 13 Web RTC
Chapter 14 Drag & Drop API
Chapter 15 App Cache API
Chapter 16 Server Sent Events Chapter 17 Miscellaneous Questions About The
Author
One Last Thing…
Chapter 1 Inheritance
Q. How to create a class?
ANSWER
JavaScript does not have a class definition. To mimic classes in JavaScript functions can
be used to declare a class.
Example :
Let’s create a student class in JavaScript which takes two parameters name and roll as
property. The code will look like below,
function Student(name,roll){ this.name = name;
this.roll = roll;
}
Q. How to create an object?
ANSWER
An object in JavaScript can be created using two ways:
New Keyword:
To create a student object from the above student class we can call the Student function
using new keyword.
var student1 = new Student(‘sandeep’,2)
Anonymous Object:
Anonymous objects can be created using pair of curly braces containing property name
and value pairs.
Var rose = {‘color’: ’red’}

Q. How to declare a private and a public member?


Private members are declared using var keyword and constructor function.
function Student(name,roll){ var id= ABCD123;
this.name = name;
this.roll = roll;
}
When a Student object will be created the propertied name and roll will be accessible
using dot operator but id will not be accessible as it behaves as a private member and
return undefined on call.
The above chrome console is showing a student1 object is created.name property is
accessible as it is showing sandeep on student1.name call. So name is a public property for
the student object. But id property is not accessible and returned undefined on student1.id
call. This shows id is a private property in student1 object.
Q. What is prototype property?
By Using Prototype we can add new members to an existing object. Every JavaScript
object has this property internally. Initially it is an empty object.
Example:
function Student(name,roll){
this.name = name;
this.roll = roll;
}
var student1 = new Student(‘sangeeta’,30); Student.prototype.mark = 100;
Checkout the below chrome console for the use of protype.
Initially the student1 object has only two properties name and roll. By using prototype a
new property mark has been added to student object with a value of 100.Now the console
shows that the mark property is also added to the existing student1 object.
Q. What is constructor property?
ANSWER
Constructor property of an object maintains a reference to its creator function.
Example:
Let us checkout an example by creating a student object and calling the constructor
property on it.
function Student(name, mark){
this.name=name;
this.mark =mark;
}
var student1 = new Student(‘sandeep’,123); console.log(student1.constructor);
Checkout the following screen shot for above code in chrome console. The console log is
printing the referenced function by student1 object.
Q. How to call other class methods?
ANSWER
Using call() and apply() method we can use methods from different context to the current
context. It is really helpful in reusability of code and context binding.
call() : It is used to calls a function with a given this value and arguments provided
individually.
apply(): It is used to call a function with a given this value and arguments provided as an
array.
Below code has two function getTypeOfNumber() and getTypeOfAllNumber(). The
details pf these functions are below. getTypeOfNumber : This method takes single
number as
parameter and return the type either Even or Odd.
getTypeOfAllNumber : This method takes array of numbers
as parameter and return the types in an array with Even or
Odd.
var MyNumber = {
getTypeOfNumber : function(number){
var type = (number % 2 === 0) ? “Even” : “Odd”; return type;
},
getTypeOfAllNumber : function (){
var result = [],i=0;
for (; i < arguments.length; i++){
var type =
MyNumber.getTypeOfNumber.call(null,arguments[i]) ;
result.push(type)
}
return result;
}
};
var typeOfNumber =
MyNumber.getTypeOfNumber.call(null,21) console.log(typeOfNumber)
var typeOfAllNumber =
MyNumber.getTypeOfAllNumber.apply(null,[2,4,5,7 8,21])
console.log(typeOfAllNumber)
Below screenshot shows output of the above code Firebug console.

Q. Explain method overriding with an Example?


ANSWER
We can override any inbuilt method of JavaScript by declaring its definition again. The
existing definition is accessible to override by the prototype property. Consider the below
example, split() is an built-in method for a string object .Its default behaviour to break the
specified string to an array and is a member function of String class. But we have
overridden its definition using its prototype property.
Below screenshot shows the inbuilt behaviour of split() method. It has divided the string
into an array of element.

The following screenshot shows the new overridden definition of split () method. It is now
normally returns string “I am overriden”.

Q. How to inherit from a class?


ANSWER
Inheritance can be achieved in JavaScript using prototype property.
We need to follow 2 steps to create an inheritance.
Step1:
Child class prototype should point to parent class object.
<ChildClassName>.prototype = new <ParentClass>();
Step2:
Reset the child class prototype constructor to point self.
<ChildClassName>.prototype.constructor=<ChildClassName>
Example:
Below example shows ScienceStudent class as a child class of Student class. As the
method showMyType() is available for ScienceStudent object.
function Student(name){
this.name=name;
}
Student.prototype.sayMyType = function(){
console.log(“I am student type”)
}
function ScienceStudent(name){
}
ScienceStudent.prototype = new Student();
ScienceStudent.prototype.constructor = ScienceStudent;
var student2 = new ScienceStudent(‘sangeeta’);
console.log(student2.sayMyType());
Check out the below screen shot for the output of the above code in the developer console.
To test the type of an object belongs to a class or not instanceOf can be used. This returns
a Boolean value, TRUE for an object belongs to a class or else FALSE. Check the below
screen shot for the test of student2 object using instanceOf.

Q. What is differential inheritance?


ANSWER
Differential Inheritance is a common prototype-oriented model that uses the concept that
most objects are derived from other, more generic objects, and only differ in a few small
aspects. Each object maintains a reference to its prototype and a table of properties that are
different.
Q. What is Object.create() method do?
ANSWER
ECMAScript 5.1 has this method in its specification. This method can be used to create a
new object with given prototype object and properties. The syntax of this method is listed
below.
Object.create(proto[, propertiesObject])
Example:
Below code has a Student class function with name property and the prototype object has
a method getStudentName() which return the name of the student. A new student1 object has
been creates using Object.create() method by passing the prototype object of Student with
value of the name as sandeep. Then the getStudentName() method is called on student1 object
and logged in the console.
function Student(name) {
this.name = name;
}
Student.prototype = {
getStudentName: function() {
return “Name of Student is :” + this.name; }
};
var student1 = Object.create(Student.prototype); student1.name = “Sandeep”;
console.log(student1.getStudentName());
The following screenshot shows the output of the above code in the developer console.

Q. Write a polyfill for Object.create() method if it is not present in the browser?


ANSWER
ECMAScript 5.1 has this method in its specification. If the browser is old then Object.create()
method is not present.To resolve this we need to write a polyfill. Below code shows the
polyfill for Object.create() method.
//check if create method is present inside Object if (typeof Object.create != ‘function’) {
//define the create method
Object.create = (function() {
var Object = function() {};
return function(prototype) {
if (arguments.length > 1) {
throw Error(‘Second argument not supported’);
}
if (typeof prototype != ‘object’) {
throw TypeError(‘Argument must be an object’);
}
Object.prototype = prototype;
var result = new Object();
Object.prototype = null;
return result; };
})();
}
The above code checks if the create() method is already present inside the Object using if
condition and comparing its type to function. If this condition true it means the create()
method is not present. Then the polyfill code block gets executes and assigns the empty
object to Object.create property.
Q. What is the purpose of Object.defineProperties() method? ANSWER
ECMAScript 5.1 provides Object.defineProperties() method to create new properties to a
defined object. It provides many configuration options to initialize these members. Below
code shows the use of this method.
function Student(name) {
this.name = name;
}
var student1 = Object.create(Student.prototype),
properties ={
“subject”: {
value: “Computer”,
writable: true,
enumerable:true
},
“marks”: {
value: 0,
writable: false,
enumerable:true
}
};
Object.defineProperties(student1, properties);
student1.name = “Sandeep”;
student1.subject =“Mathematics”;
student1.marks=75;
console.log(student1);
In the above code a student1 object created using Object.create() method. Then some new
properties like subject and marks are added to this object. The enumerable option decided
whether the property can be enumerated as own property. Writable property decides whether
the property is modifiable or not. The value property takes the default value of the property.
Below screenshot shows the output of the above code in the developer console.

Q. How can you distinguish scope and context in JavaScript? ANSWER


Scope pertains to the visibility of variables and context refers to the object to which a
method belongs and can be changed by using call or applies.
Q. What are two ways in which the variable can be assigned to an empty object?
ANSWER
When creating a new empty object, you can instantiate the Object() constructor or you can
simply create an empty object literal. In either case, you can then add properties to the
new object. The syntax of creating empty object is listed below.
var aEmptyObject= new Object();
var aEmptyObject= = {};
Chapter 2 Questions on Event
Q. How Event works?
ANSWER
Event propagation follows two phases capturing and bubbling phase.

Capturing Phase:
In this phase, event first makes its way downwards from the DOCUMENT to the target
element by passing all inner elements.
Bubbling Phase:
In this phase event makes its way back upwards from the target element to
DOCUMENT by passing all outer wrapped elements.
Q. How to attach event to an element?
ANSWER
According to DOM Level 2 Event Specification an event can be attached to an element
using addEventListener() method using three arguments.
Syntax:
<element>.addEventListener(<eventname>,<eventcallback>,<bo oleanphase>)
eventname:
Represents type of event as String parameter. For Example click, mouseover, mouseout
etc.
eventcallback :
This represents the callback function to be called for the event to be handled.
booleanphase :
This represents the phase of the event where the listener is attached. A FALSE value
represents the bubbling phase and a TRUE value represents a capturing phase.
Example:
A click event listener is added to the document which alerts a message when click occur.
document.addEventListener(‘click’, function () { alert(“Insider Event Listener”);
},false);
Q. How to attach event prior to IE9 browser version? ANSWER
In IE older bowser an event can be attached to an element using attachEvent() method.
Only For bubbling phase a listener can be added.
Syntax:
<element>.attachEvent(<eventname>,<eventcallback>)
Example:
A click event listener is added to the document which alerts a message when click occur.
Below screenshot shows adding a click event in IE 10 developer toolbar.

Except IE, the other browser added by addEventListener() method. Below screenshot
shows the demonstration this method in Firebug.

Q. How to remove event listener?


ANSWER
According to DOM Level 2 Event Specification an Event Listener can be removed using
removeEventListener() method. For IE browsers detachEvent() method must be used.
The following screenshot shows detaching click event handler from document for IE
browser.
The following screenshot shows removing click event handler from document for Firefox
browser.

Q. How setTimeOut() and clearTimeOut() function works? ANSWER


The setTimeout() method calls a function or evaluates an expression once after a
specified number of milliseconds. clearTimeOut() method stop the execution of the
function specified in the setTimeout() method.
Syntax:
var timeOut = setTimeout(function,milliseconds,lang) clearTimeout(timeOut)
Below code shows the demonstration of these time out methods.
var timeOutHandler= function(){
console.log(“inside Time Now “, new Date().getSeconds()); clearTimeout(timeOut)
}
console.log(“Time Now “, new Date().getSeconds()); var timeOut =
setTimeout(timeOutHandler,4000);
Below screenshot show the execution of the timeOutHandler() method after 4 seconds.

Q. How setInterval() and clearInterval() function works? ANSWER


The setInterval() method calls a function or evaluates an expression in specified interval
of milliseconds. clearInterval() method stop the execution of the function specified in the
setInterval() method.
Syntax:
var timeInterval = setInterval(function, milliseconds) clearInterval(timeInterval)
Below code demonstrate these interval handlers.
var counter = 0,
timeIntervaltHandler= function(){
console.log(“inside Time Now “, new Date().getSeconds()); counter++;
console.log(“Handler Called count “,counter)
if(counter === 4) {
clearInterval(timeInterval);
console.log(“Clearing the interval handler”)
}
}
console.log(“Time Now “, new Date().getSeconds()); var timeInterval =
setInterval(timeIntervaltHandler,2000);
Below screenshot shows the handler called every 2 second for 4 times .After 4th called
clearInterval() remove the execution.
Chapter 3 Closure
Q. What is Closure?
ANSWER
A closure is an inner function that has access to the outer wrapped function’s variables. It
has three different scope accesses:- Self-scope:
It has access to properties present in its own scope.
Wrapped function’s scope:
It has access to the properties present to from its enclosing function.
Global Scope:
It has access to the properties present in global scope that is window scope.
Example:
The inner function still has the access to prop1 though prop1 belongs to outer function
scope.
function myOuterFunction(){ var prop1 = 5;
return function innerFunction(){
return prop1;
}
}
var res = myOuterFunction(); console.log(res.name);
console.log(res());
Below screenshot shows the output of the above code in the console.

Q. Give an example of practical implication of closure concept? ANSWER


In web page development closures are more frequently used by the developers. A most
common scenario is when we need some kind of factory which will return a function
object with different value that can be used by application.
Example:
The following code has a background color factory named backgroundColorFactory which
returns a function with an input color. Using this factory we have created greenBackground
and blueBackground function objects and binded with the 2 buttons. Once user clicks these
buttons the background color of the body is changed to the targeted color.
<!DOCTYPE html>
<html>
<head>
<meta charset=“utf-8”>
<title>Practical Closure Example</title>
</head>
<body>
<button id=“greenButton”>Green Background</button> <button id=“blueButton”>Blue
Background</button> <script>
var backgroundColorFactory = function(color) { return function() {
document.body.style.background = color; };
};
var greenBackground = backgroundColorFactory(‘green’); var blueBackground =
backgroundColorFactory(‘blue’);
document.getElementById(‘greenButton’).onclick = greenBackground;
document.getElementById(‘blueButton’).onclick = blueBackground;
</script>
</body>
</html>
The output of the above code is listed in below screenshot.

Q. Emulate the private data using closure?


ANSWER
The following code demonstrates the declaration of private variable _name. It means we
can assign the _name value using Student constructor with a new keyword.
function Student(name) { var _name = name;
this.getName = function() { return _name;
};
}
var student1 = new Student(“Sandeep”); student1 ._name = “John”;
console.log(student1.getName());
The details of the previous code are as follows:
A Student object student1 is created with _name has value Sandeep.
A new name value John is assigned to _name but the getName() method prints Sandeep
to the console. It proves _name is private.
The following screenshot shows the Chrome console with the output of the previous code.
Chapter 4 Questions on JSON
Q. What is JSON ?
ANSWER
The JSON text format is syntactically identical to the code for creating JavaScript objects.
JSON is only a subset of JS object literal notation, but apart from looking similar, they
have nothing in common. JSON is used as data exchange format, like XML. JSON is built
on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record,
struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.
Q. Why does Google prepend while (1); to their JSON responses? ANSWER
It prevents JSON hijacking. This is to ensure some other site can’t do nasty tricks to try to
steal data. By replacing the array constructor, then including this JSON URL via a <script>
tag, a malicious thirdparty site could steal the data from the JSON response. By putting a
while(1); at the start, the script will crash instead. A same-site request using XHR and a
separate JSON parser, on the other hand, can easily ignore the while(1); prefix.
Q. What is JSONP ?
ANSWER
JSONP stands for “JSON with Padding”. It means JSON data wrapped in a function call.
A callback (processing/padding) function already defined in the Web page at the time of
requesting remote JSON data.
Example :
The below JavaScript code shows a callback function paddingFunction() for a remote URL
//abcdurl .
function paddingFunction(data){
console.log(“response data processing code”)
}
var script = document.createElement(‘script’);
script.src = ‘//abcdurl?callback=paddingFunction’
document.getElementsByTagName(‘head’)[0].appendChild(scrip t);
Q. Why use JSON over XML ?
ANSWER
The following points are in favor of JSON over XML format:
JSON can contain Integer, String, List, Arrays. XML is just nodes and elements that needs
to be parsed into Integer, String and so on before it is used by your application. JSON is
smaller, faster and lightweight compared to XML. So for data delivery between servers
and browsers, JSON is a better choice.
JSON is best for use of data in web applications from web services because of JavaScript
which supports JSON. The overhead of parsing XML nodes is more compare to a quick
look up in JSON.
For a newbie, JSON might look complex to read and understand because of its structure
unless it is well written with all brackets and commas properly indented. JSON can be
mapped more easily into object oriented system.
JSON and XML both use Unicode and thus support Internationalization.
JSON is a better data exchange format. XML is a better document exchange format.
JSON is less secure because of absence of JSON parser in browser.
If the data is in XML, you can write an XSLT template and run it over the XML to output
the data into another format: HTML, SVG, plain text, comma-delimited, even JSON.
When you have data in JSON, it’s pretty much stuck there. There’s no easy way to change
it into another data format. So here, XML scores over JSON.
Q. What is MIME type for JSON?
ANSWER
The MIME type for JSON is application/json.
Q. What data types are supported by JSON?
ANSWER
Different data types supported by JSON are Number, String, Boolean, Array, Object, null.
The following code shows a JSON object containing different data types:
{ name:“Sandeep”,
score:65,
isPassed: true,
subject: [“Computer”, “Algebra”],
address: { city:“Bangalore”, country:“India”}, email: null
}
The following screenshot shows the above JSON object in a chrome developer console
with all properties listed in key value pair.
Q. What is the role of JSON.stringify() method?
ANSWER
JSON.stringify() turns an object into a JSON text and stores that JSON text in a string.
The following screenshot shows the use of stringify() method:

Q. What is the role of JSON.parse() method?


ANSWER
The JSON.parse() method parses a string as JSON, optionally transforming the value
produced by parsing. The following screenshot shows the use of JSON.parse() method to
convert the student1 JSON string to a JSON object.

Q. What is the complete syntax of JSON.parse() method? ANSWER


The complete syntax for JSON.parse() method is as follows:
JSON.parse(text[, reviver])
The details of the above syntax are as follows:
Text: It represents the string to parse as JSON.
Reviver: It represents a function, prescribes how the value originally produced by parsing
is transformed, before being returned.
Q. How to convert date object to JSON?
ANSWER
The toJSON() method can convert the date object to JSON. The following screenshot
shows the use of toJSON() method for a date object in chrome console.
Chapter 5 Questions on DOM
Q. What is DOM ?
ANSWER
Document Object Model (DOM) is a programming API for HTML and XML document.
JavaScript is most widely used language to access these DOM API properties and
methods.
Q. What are the different objects involved in DOM ? ANSWER
According to DOM Level 2 specification it has following main objects.
Attribute : Represents an element attribute. Attributes: Represents a collection of
attribute. CDATASection : Represents an XML CDATA section. Comment: Represents
an XML comment. Document: Represents an XML document. Element: Represents an
XML element node. Node: Represents a generic node object in an XML document.
NodeList: Represents an ordered collection of node objects.
ProcessingInstruction: Represents an XML processing instruction.
TextNode: Represents an XML text node.
Q. What are the different properties involved in DOM ? ANSWER
According to DOM Level 2 specification it has following main properties
name : It has the name of the Attribute.
namespaceURI: It represents namespace URI of the node.
nextSibling: It contains the next sibling of the Node in document source order.
nodeName : This represents name of the node. nodeType: It represents type of the node.
nodeValue: It has value of the node.
ownerDocument: It has reference to the Document object that contains the Node.
ownerElement : It has reference of the Element to which the Attribute belongs.
parentNode: It represents parent Node to which the node belongs.
prefix: It represents namespace prefix of the node.
previousSibling : It has the previous sibling of the Node in document source order.
text: It has contents of all the text nodes contained by the Node and any element nodes
that it contains.
value : It has value of the Attribute.
attributes: Represents collection of Attribute objects.
childNodes : Represents NodeList collection of node objects.
data: Represents text stored within a TextNode, CDATASection, or Comment.
documentElement: It contains root element node of the document.
firstChild: This is first child of the Node in document source order.
lastChild: This is the last child of the Node object in document source order.
length: It represents number of elements in the collection.
localName: It has local name of the node..
Q. What is windows load event?
ANSWER
Load event occurs generally fired after the object is completely loaded. Window load
event is event occurs when images, script files, CSS files and other dependencies get
loaded. Below screenshot shows use of load event.

Q. What is DOM ready event?


ANSWER
DOM ready event get fired when elements are get loaded to browser. It does not wait for
images and other files loaded. We can listen to this event by attaching a callback method.
A method can be added to readyStateChange or DOMContentLoaded.The below code
shows the use of these events.
<!DOCTYPE html>
<html>
<head>
<title>Window Ready Event Example</title>
<script>
var readyHandler = function(){
var element = document.querySelector(“#message1”); element.innerHTML = “Ready
Handler Fired : readystatechange <span style=‘color:blue’>”+new Date()+”
</span>”
}
document.onreadystatechange = readyHandler; </script>
<script>
document.addEventListener(“DOMContentLoaded”,
function(event) {
var element = document.querySelector(“#message2”); element.innerHTML = ” Ready
Handler Fired :
DOMContentLoaded <span style=‘color:red’>”+new
Date()+”</span>”;
});
</script>
</head>
<body>
<h2 id=“message1”>
</h2>
<h2 id=“message2”>
</h2>
</body>
</html>
The following screenshot shows the output of the above code.

Q. What is query selector in DOM?


ANSWER
DOM provides querySelector() and querySelectorAll() methods for selecting DOM
elements. querySelector() method return a single element which matches first in the DOM.
querySelectorAll() method return a node list of matched elements. Below code
demonstrates the use of these methods in selecting elements from DOM.
<!DOCTYPE html>
<html>
<head>
<title>Document Query Selector Example</title>
</head>
<body>
<h5 class=“name”>Sandeep Kumar Patel</h5>
<h4 class=“country”>India</h4>
<h4 class=“country”>UK</h4>
<h5 class=“name”>Surabhi Patel</h5>
<h4 class=“country”>US</h4>
<h4 id=“my-score”>520</h4>
<script>
var element = document.querySelector( “#my-score” ); element.style.color=“red”;
var elements = document.querySelectorAll(“h4#my-score,
h5.name”);
for (var item of elements) {
item.style.fontStyle = “Italic”;
}
var aElement = document.querySelector( “h4.country, h4#my-score” );
aElement.style.background = “orange”;
</script>
</body>
</html>
The following screenshot shows the output of the above code in Browser.

Q. What is primary Data Type of DOM?


ANSWER
Node interface is the primary data type of DOM. It represents a single item from DOM
tree. Document, Element, CharacterData, ProcessingInstruction, DocumentFragment,
DocumentType, Notation, Entity, EntityReference interface inherits from Node interface.
Q. What is document fragment in DOM?
ANSWER
DocumentFragment is a light weight version of DOM. It does not have any parent class.
It is generally used by the developer as a temporary storage of DOM elements. Below
code shows an Example of creating document fragment and adding HTML element to it
and finally placing it to the body of the DOM.
<!DOCTYPE html>
<html>
<head>
<title>DocumentFragment Example</title>
</head>
<body>
<script>
var aFragment = document.createDocumentFragment(), aHTMLElement =
document.createElement(“h2”), aTEXTElement =
document.createTextNode(“SANDEEP”);
aHTMLElement.appendChild(aTEXTElement);
aFragment.appendChild(aHTMLElement);
document.body.appendChild(aFragment);
</script>
</body>
</html>
Below screenshot shows an h2 element with a child text node containing value SANDEEP
is place inside document fragment. Finally the document fragment is appended as a child
to the body element.
Q. Which is basic object of DOM?
ANSWER
Node is most basic object of DOM. It is the most common interface from which lot of
other DOM object are inherited. The following interfaces all inherit from Node its
methods and properties: Document, Element, CharacterData, ProcessingInstruction,
DocumentFragment, DocumentType, Notation, Entity, EntityReference. These interfaces
may return null in particular cases where the methods and properties are not relevant.
They may throw an exception - for example when adding children to a node type for
which no children can exist.
Q. What are the common doctype declarations?
ANSWER
There are 8 different type of doctype declaration and are listed below.
HTML 5: This document type is used in HTML5.
<!DOCTYPE html>
HTML 4.01 Strict : This DTD contains all HTML elements and attributes, but does NOT
INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>
HTML 4.01 Transitional : This DTD contains all HTML elements and attributes,
INCLUDING presentational and deprecated elements (like font). Framesets are not
allowed.
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
HTML 4.01 Frameset: This DTD is equal to HTML 4.01 Transitional, but allows the use
of frameset content.
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Frameset//EN”
“http://www.w3.org/TR/html4/frameset.dtd”>
XHTML 1.0 Strict : This DTD contains all HTML elements and attributes, but does NOT
INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.
The markup must also be written as well-formed XML.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
Strict//EN”
strict.dtd”>
XHTML 1.0 Transitional: This DTD contains all HTML elements and attributes,
INCLUDING presentational and deprecated elements (like font). Framesets are not
allowed. The markup must also be written as well-formed XML.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
Transitional//EN”
transitional.dtd”>
XHTML 1.0 Frameset: This DTD is equal to XHTML 1.0 Transitional, but allows the
use of frameset content.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Frameset//EN”
Frameset//EN”
frameset.dtd”>
XHTML 1.1 : This DTD is equal to XHTML 1.0 Strict, but allows you to add modules
(for example to provide ruby support for East-Asian languages).
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd” >
Chapter 6 Date Object
Q. What is a JavaScript Date Object?
ANSWER
JavaScript Date object returns time in that single moment. It contains the value in number
of milliseconds since 1 January, 1970 UTC.
Q. What are the different ways to create a Date object? Or what are the different
constructor forms of Date object?
ANSWER
JavaScript Date object has 4 overloaded constructors. These constructors are listed below.
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Q. How to get 1st January 1970 in a date object, the date from where time is gets
calculated?
ANSWER
1st January 1970 is the day from where the time is get calculated as number of
milliseconds elapsed. It can be calculated by creating a new JS object with parameter
0.below screenshot demonstrate the date object with parameter 0.

Q. How JavaScript counts months?


ANSWER
JavaScript counts months from 0 to 11 for the twelve months a year. 0 represents January
and 11 represent December. Below screenshot shows the code for today’s date that is July
23 and year 2014 and getMonth() returns 6.
Q. When RangeError invalid date exception occurs?
ANSWER
When a date object is created with invalid date string and toISOString() method is
applied to this invalid date then this RangeError occurs. Below screenshot shows ‘2014-
13-13’ string which is representing YYYY-MM-DD format where month is out of range
produces the RangeError exception.
Chapter 7 Regular Expression
Q. What is Regular Expression in JavaScript?
ANSWER
Regular expressions are used for pattern matching in a string. A regular expression in
JavaScript can be declared in two ways. Syntax for these two approaches is listed below.
var aRegExpression = new RegExp(pattern,modifiers); var aRegExpression =
/pattern/modifiers;
The details of these syntaxes are as follows:
pattern : it represents the search string.
modifiers : it represents the conditional switches that will be applied to the pattern
matching
Q. What are the methods of a regular expression?
ANSWER
There are 3 different methods for regular expressions are listed below.
exec() : scans for a matching string and returns the first matched string
test() : scans for a matching string and returns boolean value false or true.
toString() : This method returns the string value of a regular expression.
Q. What is the switch \w represents?
ANSWER
The \w represents an alphanumeric character. The following code demonstrate the use of
\w switch .
var regEx= /\wu/; var out1 = regEx.exec(“sandeep Ku Patel”), out2 = regEx.test(“sandeep
Ku Patel”);
console.log(out1);
console.log(out2);
Below screenshot shows the output of the above code which pattern match any substring
having alphanumeric character with 2nd character as u.

Q. Write a Regular expression to reverse the first and last name? For example Sandeep
Patel becomes Patel Sandeep.
ANSWER
To reverse first and last name we have to use replace() function on input string with
regular expression. The following code shows the method to reverse first and last name.
var reverseFirstLastName = function(nameString){
var regex = /(\w+)\s(\w+)/,
resultString = nameString.replace(regex, ‘$2 $1’);
return resultString;
};
var inputName = “Sandeep Patel”,
output = reverseFirstLastName(inputName);
console.log(output);
The following screenshot shows the chrome console executing above code and output is
printed on console.

Q. Write a Regular expression to validate email address? ANSWER


To validate email we have to use test() method on input string which returns true or false
on execution. The following code shows the method to validate email string.
function validateEmail(email) {
var re =
/^(([^<>()[\]\.,;:\s@"]+(.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\
/^(([^<>()[\]\.,;:\s@"]+(.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\

9]+.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
var email1 = “sandeeppateltech@gmail.com”,
email2 = “sandeep@@gmail.com”,
result1 = validateEmail(email1),
result2 = validateEmail(email2);
console.log(result1);
The following screenshot shows the output of the email validation code in a chrome
developer console.
Q. Write a Regular expression to validate a URL ?
ANSWER
For validating URL we have considered the protocol will be either http/https/ftp and it
must start with WWW word .Considering these points the javascript code for validating a
URL is as follows.
function validateURL(url) {
var regExUrl = new RegExp(“(http|ftp|https)://[\w-]+(.[\w
]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?”); return regExUrl.test(url);
};
var url1 = “http://www.google.com”,
url2 = “htttp://www.google.com”,
result1 = validateURL(url1),
result2 = validateURL(url2);
console.log(result2);
The following screenshot shows the chrome console with URL validation code in
execution for a given URL.
Chapter 8 Questions on Canvas API
Q. What is a canvas in HTML5?
ANSWER
Canvas is a new element in HTML5 for drawing graphics. A graphics can be drawn on
canvas by following below steps.
Define the canvas area.
Get the drawing context.
Using the context start the drawing.
Q. What is the difference between Canvas and SVG?
ANSWER
Difference between Canvas and SVG (Scalable Vector Graphics) are listed in below table.
CANVAS SVG
i. A diagram can be drawn i. using a context in
Canvas.
ii. A diagram drawn in ii. canvas is resolution
dependent.
iii. A diagram drawn in iii. Canvas can be saved to
PNG or JPG format.
iv. Diagram drawn in Canvas iv. is pixel based. No DOM
elements are involved.
v. Rendering game v. graphics, such as sprites and backgrounds can be created.
A diagram is drawn using XML like SVG element.
A diagram drawn in SVG is resolution
independent.
SVG diagrams cannot be saved to PNG or JPG format.
Diagram drawn in SVG is DOM element based. No pixels are involved in the diagram.
Highly interactive
animated user interfaces can be created.
vi. Poor text rendering vi.
capabilities
vii. Poor SEO and vii. Accessibility as
everything pixel based
and content are not
accessible.
viii. Modified through script viii. only.
ix. Performance is better ix. with smaller surface, a
larger number of objects (>10k), or both.
Good text rendering capabilities
Better SEO and
Accessibility as it DOM based rendering.
Modified through script and CSS.
Performance is better with smaller number of objects (<10k), a larger surface, or both.
Q. What is canvas 2d context and how it is created?
ANSWER’
Using getContext() method with parameter ‘2d’ a canvas context can be created.
This context method is a type of CanvasRenderingContext2D object. Below code shows
a simple 2d context creation and log the object’s constructor.
<html>
<body>
<canvas id=“myCanvas”></canvas>
<script>
var canvas = document.getElementById(“myCanvas”), context =
canvas.getContext(“2d”);
console.log(context.constructor);
</script>
</body>
</html>
The following screenshot shows the constructor function of the context object which is
CanvasRenderingContext2D native object.

Q. How to load an image in Canvas?


ANSWER
An image can be loaded using drawImage() method. This method takes several inputs for
drawing an image. These parameters are positioning and clipping type. We will discuss
these parameters in separate question. Below code shows how to use the drawImage()
method to load a PNG image from a URL inside the canvas.
<html>
<body>
<canvas id=“myCanvas”></canvas>
<script>
var canvas = document.getElementById(“myCanvas”), context =
canvas.getContext(“2d”),
img = new Image();
img.src =
“http://www.gravatar.com/avatar/4205261332ff131e971b48db
31dcb528.png”;
img.onload = function() {
context.drawImage(img, 10, 10);
};
</script>
</body>
</html>
Below screenshot shows the Gravatar image getting drawn inside the HTML5 canvas
element. This drawing is done using 2d context.

Q. what are the different overloaded signature for drawImage() method?


ANSWER
The drawImage() method has 3 different signature and listed below.
drawImage(img, x, y) :This method position the image on the canvas at <x, y>
coordinates.
drawImage(img, x, y, width, height) : This method position the image on the canvas at
<x, y> coordinates with a specified height.
drawImage(img, sx, sy, swidth, sheight, x, y, width, height) : This method clipped the
image with starting point <sx, sy> having height sheight and width swidth and position it
at <x, y> coordinates with a specified height and width.
Chapter 9 Geo Location API
Q. What is Geo Location API?
ANSWER
Geo Location API publishes the location of the user to the web. It needs user’s permission
for privacy reason. The Geo location API is present inside navigator.geolocation object.
Q. How to determine Geo Location API is supported in browser? ANSWER
To determine Geo location API is supported in browser can be determined by the truth
value of geolocation object inside the navigator object. Below code has the function which
returns true or false Boolean value based on the geolocation object present inside the
navigator.
function isGeoLocationSupported(){
var flag = navigator.geolocation ? true : false; return flag;
}
var isSupported = isGeoLocationSupported(); if(isSupported){
console.log(navigator.geolocation);
}else{
console.log(“Geo Location API not supprted”); }
The following screenshot shows the output of the above code as the geolocation object is
present inside the navigator API.
Chapter 10 Web Workers
Q. What is a Web Worker?
ANSWER
Web Workers are new HTML5 feature to achieve concurrency in JavaScript execution in
web application. A web worker is JavaScript file which run in the background of the
browser without impacting the page performance. This helps in resolve the age old
problem “Un responsive script alert box”. Generally these workers can be used for
extensive computation purpose.
Q. How to detect Web Worker is supported by browser? ANSWER
We can check the support of Web Worker in a browser by validating the Worker property
is present in the window object. Code for checking Web Worker support is as follows:
<!DOCTYPE html>
<html>
<head lang=“en”>
<title>Web Worker</title>
</head>
<body>
<script>
var isWorkerSupported = window.Worker ? true : false; console.log(“Is Web Worker
Supported:
“+isWorkerSupported);
</script>
</body>
</html>
In the previous code isWorkerSupported variable can contain TRUE or FALSE value based on the
existence of Worker property inside window object. The following screenshot shows the
output of above code in chrome console.

Q. What is a dedicated worker?


ANSWER
A dedicated worker is only accessible by the calling script. A dedicated worker object can
be created using worker constructor. Syntax for creating a new dedicated worker is listed
below.
var aDedicatedWorker = new Worker(“script.js”)
The parameter inside the Worker object is the JavaScript file which will run as worker in
the background of the browser.
Q. What is a shared worker?
ANSWER
A Shared Worker can be accessed by multiple scripts. A shared worker is accessible by
different window, iframe and by other worker having same origin. Syntax for creating a
new dedicated worker is as follows.
var aSharedWorker = new SharedWorker(“script.js”)
The parameter inside the Worker object is the JavaScript file which will run as shared
worker in the background of the browser.
Q. Develop a dedicated worker to display the time?
ANSWER
Let’s create the time worker in dateWorker.js file and we can call this worker in
dateWorkerDemo.html file. The following code shows the content of dateWorker.js file
which listens to the messages and posts the current time in every second.
self .addEventListener(“message”,function(event){ setInterval(function(){
var time = new Date();
self.postMessage({
hour :time.getHours(),
minute: time.getMinutes(),
second: time.getSeconds()
});
},1000
);
});

The following code shows the content of dateWorkerDemo.html containing creation of


worker instance and listening to worker response.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Time Web Worker Demo</title> </head>
<body>
<h1 id=“resultContainer”></h1>
<button id=“timeButton”>Get Time</button>
< script>
var dateWorker = new Worker(“dateWorker.js”),
resultContainer = document.getElementById(“resultContainer”), timeButton =
document.getElementById(“timeButton”);
timeButton .addEventListener(“click”,function(){
dateWorker.postMessage(null);
});
dateWorker.addEventListener(“message”,function(workerEvent){ var responseData = workerEvent.data,
hour = responseData.hour,
minute = responseData.minute,
second = responseData.second;
resultContainer.innerText = “HOUR: “+hour +
” MINUTE: “ +minute +” SECOND: “+second; });
</script>
</body>
</html>
The output of the preceding code shown in following screenshot with hour, minute and
second is displayed from the worker response messages.

Q. Develop a dedicated worker to find square of a number? ANSWER


The definition of square worker is present in doSquareWorker.js file and listens to
message and generates the square of number. The square worker is instantiated in
squareWorkerDemo.html file which listens to the response from the square worker and
prints it in browser.The code content of doSquareWorker.js file are as follows.
self .addEventListener(“message”,function(event){
var inputData = event.data,
inputNumber = parseInt(inputData.number,10),
squareResult = Math.pow(inputNumber,2);
self.postMessage({result
:squareResult});
});
The squareWorkerDemo.html file has the following code.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Square Web Worker Demo</title> </head>
<body>
<h1 id=“resultContainer”></h1>
< input type=“number” id=“inputNumber” placeholder=“Enter a number” value=“5”>
<button id=“squareButton”> SQUARE</button>
< script>
var squareWorker = new Worker(“doSquareWorker.js”), resultContainer =
document.getElementById(“resultContainer”), squareButton = document.getElementById(“squareButton”),
inputNumber=document.getElementById(“inputNumber”);
squareButton .addEventListener(“click”,function(){ squareWorker.postMessage({number:inputNumber.value});
});
squareWorker.addEventListener(“message”,function(workerEvent){ var responseData = workerEvent.data,
squareResult= responseData.result;
resultContainer.innerText = squareResult;
});
</ script>
</body>
</html>

The output of the preceding code shown in following screenshot with square of a number
is displayed from the worker response messages.

Q. How to define an inline web worker? Demonstrate an inline worker for multiplying 2
numbers?
ANSWER
An inline web worker can be defined inside a HTML markup using <script> tag with type
attribute having value javascript/worker. Syntax:
< script type=“javascript/worker”>
//JavaScript Code for defining a worker
</script>

Example:
The inlineWorkerDemo.html file contains the code for defining multiplication worker
which listens to the messages and calculates the multiplication and post the response. The
listener to the multiply worker extracts the result and renders in the browser. The
following code shows the content of inlineWorkerDemo.html file.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Inline Web Worker Demo</title>
</head>
<body>
<h1 id=“resultContainer”></h1>
<input type=“number” id=“number1” value=“8” placeholder=“Enter first number”> <input type=“number”
id=“number2” value=“10” placeholder=“Enter second number”>
<button id=“multiplyButton”>Multiply</button>
<script id=“multiplyWorker” type=“javascript/worker”>
self.addEventListener(“message”,function(event){
var requestData = event.data,
number1 = requestData.number1,
number2 = requestData.number2,
multiplyResult = number1 * number2;
self.postMessage({result:multiplyResult});
});
</script>
<script>
var textContent = document.querySelector(‘#multiplyWorker’).textContent, workerBlob = new Blob([textContent]),
workerURL = window.URL.createObjectURL(workerBlob), multiplyWorker = new Worker(workerURL),
resultContainer = document.getElementById(“resultContainer”), multiplyButton =
document.getElementById(“multiplyButton”), number1 = document.getElementById(“number1”),
number2 = document.getElementById(“number2”);
multiplyButton.addEventListener(“click”, function () {
multiplyWorker.postMessage({
number1:parseInt(number1.value,10),
number2: parseInt(number2.value,10)
});
});
multiplyWorker.addEventListener(“message”, function (workerEvent) {
var responseData = workerEvent.data,
result = responseData.result;
resultContainer.innerText = “Result: ” + result;
});
</script>
</body>
</html>

User can input two numbers in the text box and press the multiply button. The multiply
worker calculate the multiplication and result is rendered in the browser. The outputs of
the preceding code are rendered as following screenshot.

Q. How to handle error in web worker?


ANSWER
We can throw error using throw keyword from the web worker. A callback method can be
attached to the error event to handle the generated error. The
positiveNoSqaureWorkerDemo.html file contains a worker which takes only positive
number as input. If a negative number is passed it throws an error. The code content of this
file is as follows.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Web Worker Error Handler Demo</title>
</head>
<body>
<h1 id=“resultContainer”></h1>
<input type=“number” id=“number1” value=“-4” placeholder=“Enter a number”> <button
id=“squareResult”>Square</button>
<script id=“squareWorker” type=“javascript/worker”>
self.addEventListener(“message”,function(event){
var requestData = event.data,
number1 = requestData.number1,
squareResult = 0;
if(number1>0) {
squareResult = number1 * number1
self.postMessage({result:squareResult});
} else{
//For negative number throw error
throw “It is a negative number.Please supply a positive number.”; }
});
</script>
<script>
var textContent = document.querySelector(‘#squareWorker’).textContent,
workerBlob = new Blob([textContent]),
workerURL = window.URL.createObjectURL(workerBlob),
squareWorker = new Worker(workerURL),
resultContainer = document.getElementById(“resultContainer”),
squareResult = document.getElementById(“squareResult”),
number1 = document.getElementById(“number1”),
number2 = document.getElementById(“number2”);
squareResult.addEventListener(“click”, function () {
squareWorker.postMessage({
number1:parseInt(number1.value,10)
});
});
//Success Handler for the worker
squareWorker.addEventListener(“message”, function (workerEvent) { var responseData = workerEvent.data,
result = responseData.result;
resultContainer.innerText = “Result: “ + result;
});
//Error Handler for the worker
squareWorker.addEventListener(‘error’, function(workerErrorEvent){ resultContainer.innerText = “Error: “ +
workerErrorEvent.message; }, false);
</script>
</body>
</html>
The output of the above code is rendered as following screenshot rendering the error
message in the browser.
Q. How to import an external script in web worker? Demonstrate it with an example?
ANSWER
To import external script inside a web worker we need to use importScripts() method
with a file name as input parameter. To demonstrate import script functionality we have
created 3 files greatest-number-script.js, numberWorker.js,
numberWorkerDemo.html file. The following screenshot shows these files.

The greatest-number-script.js is the external script that we need to import it to our web
worker. It has a single method
findGreatestNumber() method to find out a bigger number among two supplied
numbers. The following code shows the content of greatest-number-script.js file.
var findGreatestNumber = function(number1,number2){
return number1>number2 ? number1 : number2;
};

The numberWorker.js file contains the code for importing the external script inside the
web worker message listener callback method. The following code shows the content of
numberWorker.js file.
self .addEventListener(“message”,function(event){
var numberWorker = self.importScripts(‘greatest-number-script.js’); var requestData = event.data,
number1 = requestData.number1,
number2 = requestData.number2,

greatestNumber = findGreatestNumber(number1,number2); self.postMessage({result


:greatestNumber});
});

The numberWorkerDemo.html file contains the code for instantiating the number web
worker and listening to response message. The following code shows the content of
numberWorkerDemo.html file.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Time Web Worker Demo</title>
</head>
<body>
<h1 id=“resultContainer”></h1>
<input type=“number” id=“number1” value=“7” placeholder=“Enter first number”> <input type=“number”
id=“number2” value=“9” placeholder=“Enter second number”>
<button id=“greatButton”>Find Greatest Number</button>
<script>
var numberWorker = new Worker(“numberWorker.js”),
resultContainer = document.getElementById(“resultContainer”), greatButton =
document.getElementById(“greatButton”),
number1 = document.getElementById(“number1”),
number2=document.getElementById(“number2”);
greatButton.addEventListener(“click”,function(){
numberWorker.postMessage({
number1:parseInt(number1.value,10),
number2: parseInt(number2.value,10)
});
});
numberWorker.addEventListener(“message”,function(workerEvent){ var responseData = workerEvent.data;
resultContainer.innerText = “Greatest Number: “+responseData.result;
});
</script>
</body>
</html>
The output of this code is rendered as following screenshot containing the greatest number
from the supplied numbers.

Q. Create a shared worker to calculate the length of a string? ANSWER


The calculateLengthWorker.js contains the code for listening messages and calculates
the length of input string. The shared worker listens to message in a port by listening to
connect event. The code for calculateLengthWorker.js file is as follows.
self .addEventListener(“connect”, function (event) {
var port = event.ports[0];
port.addEventListener(“message”, function (event) {
var requestData = event.data,
inputString = requestData.string,
stringLength = inputString.length;
port .postMessage({result:stringLength});
}, false);
port.start();
}, false
);

The lengthWorkerDemo.html file contains the code for instantiating the shared worker
and rendering the response in browser. The code content of lengthWorkerDemo.html file
are listed as follows.
<!DOCTYPE html>
<html>
<head lang=“en”>
< meta charset=“UTF-8”>
<title>Shared Web Worker Demo</title> </head>
<body>
< h1 id=“resultContainer”></h1>
<input type=“text” id=“inputString” value=“Hello” placeholder=“Enter a string”> <button id=“lengthButton”>Get
Length</button>
<script>
var lengthWorker = new SharedWorker(“calculateLengthWorker.js”), resultContainer =
document.getElementById(“resultContainer”), lengthButton = document.getElementById(“lengthButton”), inputString
= document.getElementById(“inputString”);
lengthButton .addEventListener(“click”, function () {
resultContainer.innerText = ””;
lengthWorker.port.postMessage({
string :inputString.value
});
});
//start the worker
lengthWorker.port.start();
//Success Handler for the worker
lengthWorker.port.addEventListener(“message”, function (workerEvent) {
var responseData = workerEvent.data,
result = responseData.result;
resultContainer.innerText = “Result: ” + result;
});
</script>
</body>
</html>
The output of the preceding code is rendered as following screenshot displaying length of
the input string.
Chapter 11 Local Storage
Q. What is local storage?
ANSWER
HTML5 provides a feature to store data locally in end user’s browser. Data is stored in the
browser as key-value pair. Unlike cookie it has average space of 5 MB. This storage
comes in 2 different type sessionStorage and localStorage.
localStorage : it stores data with no expiration date. sessionStorage : it stores data with
an expiration date.
Q. Which one is the main Storage interface?
ANSWER
window.Storage() is the main interface from where the localStorage and sessionStorage
are implemented. This interface has the below definition.
interface Storage {
readonly attribute unsigned long length;
DOMString? key(unsigned long index);
getter DOMString? getItem(DOMString key);
setter creator void setItem(DOMString key, DOMString value); deleter void
removeItem(DOMString key);
void clear();
}
The details of the above code are as follows:
setItem(key,value) : This methods stored the value in storage using key-value pair.
getItem(key) : This method retrieves the stored object using the key.
removeItem(key) : This methods removes the stored item based on the key.
clear() : Deletes all the items from the storage. length : This property returns the length of
the storage, no of elements inside the storage.
key(position) : This method returns the key for the value in the given numeric position.
Q. How to store and retrieve an object in local storage? ANSWER
Local storage provides setItem() and getItem() for storing and retrieving an object from
the storage. setItem(key, value) method takes 2 input parameter to store the object. The
getItem(key) method retrieves the value using key as input parameter. Below code shows
the storing “Sandeep Kumar” string in “myName” key and then retrieves this string
place it in a HTML element.
<!DOCTYPE html>
<html>
<body>
<div id=“resultContainer”>
</div>
<script>
var container =
document.getElementById(“resultContainer”);
localStorage.setItem(“myName”, “Sandeep Kumar”); container.innerHTML =
localStorage.getItem(“myName”); </script>
</body>
</html>
Below screenshot shows the chrome developer storage preview which holds the above
object as key and value pair.

Q. How to attach an event to a local storage?


ANSWER
When local storage objects get modified a storage event is fired. A callback method can be
attached to window object using addEventListener() or attachEvent() method.
NOTE:
When the setItem(), removeItem(), and clear() methods are called on a Storage object x
that is associated with a local storage area, if the methods did something, then in every
Document object whose Window object’s localStorage attribute’s Storage object is
associated with the same storage area, other than x, a storage event must be fired.
In simple sentence, a storage event is fired on every
window/tab except for the one that updated
the localStorage object and caused the event. Below code has a callback method listening
to storage event. When the button is clicked in one of the tab to update the local storage
object the storage event listener in the other tab got triggered and content is updated.
<!DOCTYPE html>
<html>
<body>
<div id=“resultContainer”> </div>
<button onclick=“update()”>Click Me</button> <script>
var container =
document.getElementById(“resultContainer”), methodStorageEvent = function(event){
container.innerHTML = “Event
Fired”+localStorage.getItem(“myName”) ;
},
counter = 1,
update = function(){
localStorage.setItem(“myName”, ++counter); container.innerHTML =
localStorage.getItem(“myName”) ;
};
window.addEventListener(“storage”,
methodStorageEvent,false)
</script>
</body>
</html>
Below screenshot demonstrates how the storage event is fired and the other tabs which
accessing the same page receives the storage event and update their content.
Chapter 12 File API
Q. What is HTML5 File API?
ANSWER
HTML5 provides new API to work with files inside a browser. This API provides File,
FileList and Blob data type to work with files. It provide FileReader interface to read files
asynchronously.
Q. What are the methods provided by FileReader for asynchronous read?
ANSWER
FileReader provides 4 different methods to work with loaded files. These asynchronous
methods are listed as follows.
readAsBinaryString(Blob | File) : Reads the target file and save it to binary string
containing integer of range 0-255.
readAsText(Blob | File, opt_encoding): Reads the target file and save it as UTF-8 text
file.
readAsDataURL(Blob | File) : Reads the target file and returns a data URL containing
base64 ascii string. readAsArrayBuffer(Blob | File) : Reads the target file and save it in a
array buffer.
Q. What is Blob object in javascript?
ANSWER
A blob object refers to a sequence of bytes representing data. The IDL(Interface Definition
Syntax) for Blob object is as follows:
interface Blob {
readonly attribute unsigned long long size; readonly attribute DOMString type; Blob
slice(optional [Clamp] long long start,
optional [Clamp] long long end, optional DOMString contentType); void close();
};
The details of the method and properties are as follows: slice method : The slice method
returns a new Blob object
with bytes ranging from the optional start parameter up to but not including the optional
end parameter, and with a type attribute that is the value of the optional contentType
parameter
close method : The close method must permanently neuter the original Blob object. This
is an irreversible and nonidempotent operation; once a Blob has been neutered, it cannot
be used again; dereferencing a Blob URL bound to a Blob object on which close has been
called results in a network error. A neutered Blob must have a size of 0.
size property: It returns the size of the Blob object in bytes. type property: It returns the
type of the content that the Blob object holds.
Q. How to create a Blob Object?
ANSWER
A blob object can be created using new keyword with Blob constructor. A Blob
constructor takes the following parameters:
Blob part sequence: This can be either ArrayBuffer, ArrayBufferView, Blob and
DOMString
Blob property bag : It takes one parameter representing type of the ASCII-encoded string
in lower case representing the media type of the Blob.
The following code shows an example of creating Blob using new keyword:
var a = new Blob();
var b = new Blob([“foobarbazetcetc” + “birdiebirdieboo”], {type:
“text/plain;charset=UTF-8”});
Q. What are readable states for a Blob object?
ANSWER
A Blob must have a readability state, which is one of OPENED or CLOSED.
A Blob that refers to a byte sequence, including one of 0 bytes, is said to be in the
OPENED readability state.
A Blob is said to be closed if its close method has been called. A Blob that is closed is said
to be in the CLOSED readability state.
Q. What are different states of FileReader?
ANSWER
The FileReader object can be in one of 3 states. The readyState attribute, on getting, must
return the current state, which must be one of the following values:
EMPTY : The FileReader object has been constructed, and there are no pending reads.
None of the read methods have been called. This is the default state of a newly minted
FileReader object, until one of the read methods have been called on it.
LOADING : A File or Blob is being read. One of the read methods is being processed,
and no error has occurred during the read.
DONE : The entire File or Blob has been read into memory, OR a file error occurred
during read, OR the read was aborted using abort(). The FileReader is no longer reading a
File or Blob. If readyState is set to DONE it means at least one of the read methods have
been called on this FileReader.
Chapter 13 Web RTC
Q. What is Web RTC?
ANSWER
Web RTC provides the capability to browsers for real time communication without any
additional plugin installed. It involves audio, video and other type of data streaming
among the browser with their native capability.
Q. What is the API implemented by Web RTC?
ANSWER
Web RTC implements three different API. These interfaces are listed below.
MediaStream : This represents a synchronized media stream using camera and
microphone.
RTCPeerConnection : This interface is responsible for stable connection between peer
browser during real time communication.
RTCDataChannel : This interface is responsible for other type of data communication
between peer browser. For example the remote desktop sharing using browser.
Q . What is MediaStream?
ANSWER
MediaStream basically represents the stream captured by Camera and microphone. Each
MediaStream has an input which captures the stream. This MediaStream can be accessed
using navigator.getUserMedia() method.
Q . What are the input parameters to getUserMedia() method? ANSWER
The getUserMedia() method takes 3 parameters as input. These parameters are as
follows:
Constraint Object similar to a configuration object. Success Callback Method.
Error Callback Method.
Q. What are MediaStreamTracks?
ANSWER
The MediaStream returned by getUserMedia() has 2 useful methods getAudioTracks()
and getVideoTracks().Both of these methods returns an array of MediaStramTracks.
Q . What are the protocols used by Web RTC for
communication?
ANSWER
Web RTC uses 2 different protocols for communication. These 2 protocols are listed as
follows.
DTLS: Datagram Transport Layer Security.
SRTP: Secure Real-time Transport Protocol.
Q . How to view the statistics of an in progress Web RTC session in Chrome browser?
ANSWER
We can view the detail statistics and charts of an ongoing Web RTC session in chrome
browser by using chrome://webrtc-internals/ in chrome browser.
Q . What are the different event handlers for a channel? ANSWER
A channel has 4 different event handlers. These event handlers are as follows.
Onopen : Executed when the connection is established. Onerror: Executed if there is an
error creating the connection.
Onmessage: When you receive a message, this method will execute
Oclose: Executed if the other peer closes the connection.
Q . What is a signal channel?
ANSWER
WebRTC can’t create connections without some sort of server in the middle. We call this
the Signal Channel.
Q . What is an ICE technique?
ANSWER
Interactive Connectivity Establishment (ICE) is a technique used in computer networking
involving network address translators (NATs) in Internet applications of Voice over
Internet Protocol (VoIP), peer-to-peer communications, video, instant messaging and other
interactive media.
Q. What is an ICE Candidate?
ANSWER
While communication peers must exchange information about the network connection.
This is known as an ICE candidate.
Q . What are the server side functionalities needed by the Web RTC?
ANSWER
Web RTC requires following functionalities from server side to create a communication
between peers.
User discovery and communication.
Signaling.
NAT/firewall traversal.
Relay servers in case peer-to-peer communication fails.
Q. What is STUN protocol? ANSWER
STUN (Session Traversal Utilities for NAT) is a standardized set of methods and a
network protocol to allow an end host to discover its public IP address if it is located
behind a NAT.
Chapter 14 Drag & Drop API
Q. How to make content draggable inside the browser? ANSWER
HTML5 provides drag and drop feature. An element can be made draggable by setting its
draggable property to true. Check the below code having 2 buttons. One button is
draggable and other is just a normal button.
<!DOCTYPE html>
<html>
<head>
<title>Draggable Element</title>
</head>
<body>
<button draggable=“true”>Draggable Button</button> <button>Normal Button</button>
</body>
</html>
Below screenshot shows both these buttons. The draggable button is movable while the
normal button is fixed in its position.

Q. What happens when drag starts for an element?


ANSWER
There are 3 important key points to note when a drag starts. These key points are as
follows.
Drag Data: It represent the type of data that will be transferred while dragging
Drag Feedback: This represents image which appears beside the mouse pointer during
the drag operation. Drag Effect: This represents the type of drag happens to element. It
can be 3 types and listed below.
Copy: This effect indicates that the
data being dragged will be copied from its present location to the drop location.
Move: This effect indicates that the data being dragged will be moved from its original
position to drop
location.
Link: This effect indicates that some form of relationship or connection will be created
between the source and drop locations.
Q. What are the Drag and drop events?
ANSWER
There are 7 different drag and drop events that can be attached
with a callback method programmatically.
Dragstart: it is fired on an element when a drag is started Dragenter: it is fired when the
mouse enters an element while a drag is occurring.
Dragover: This event is fired as the mouse is moving over an element when a drag is
occurring.
Dragleave : This event is fired when the mouse leaves an element while a drag is
occurring.
Drop: The drop event is fired on the element where the drop occurred at the end of the
drag operation.
Dragend: The source of the drag will receive a dragend event when the drag operation is
complete, whether it was successful or not.
Q. What is a dataTransfer property?
ANSWER
dataTransfer object holds the piece of data sent in a drag action. dataTransfer is set in the
dragstart event and read/handled in the drop event. The syntax for setting value in
dataTransfer object is as follows.
event.dataTransfer.setData(format, data)
The above syntax will set the object’s content to the mime type and data payload passed as
arguments.
Q. Develop an example to drag and drop an element from one place to another?
ANSWER
To demonstrate drag and drop we have created div element with rounded border and
background color red. We will drag this element and drop it in a container. The following
code shows the drag and drop example.
<!DOCTYPE HTML>
<html>
<head>
< style>
#ball{
width:50px;
height:50px;
background: red; border-radius: 100%;
}
#dropZone {
width:200px;
height:100px;
padding:10px;
border:1px solid #aaaaaa;
}
</style>
</head>
<body>
<div id=“dropZone”
ondrop=“drop(event)”
ondragover=“allowDrop(event)”>
</div>
<br>
<div id=“ball”
draggable=“true”
ondragstart=“drag(event)”></div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData(“text”, ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData(“text”);
ev.target.appendChild(document.getElementById(data));
}
</script>
</body>
</html>

The output of the code looks like following screenshot before dragging with both the
element are in there original position.
The output of the code looks like following screenshot after dragging and dropping the
draggable element to the container.
Chapter 15 App Cache API
Q. What is app cache? What are the benefits of using app cache API in a web application?
ANSWER
App cache API is the new feature provided by the HTML5.This API power up a web
application working without an internet connection. The most important benefits by this
API are listed below:
Speed : Like all other cache it increases the speed of accessing the page content.
Offline browsing: It increases the usability of application as it can be accessed without
internet.
Reduced load: As the content and data is now cache in the browser the load of the
application is reduced form the server.
Few network calls: As most of reusable content is present in app cache it this reduces the
no of network call to the server.
Q. How to enable application cache in an html file?
ANSWER
To enable application cache in a HTML file we need to have manifest attribute in
<HTML> element containing the name of the appcache file. The syntax of declaring
application cache in HTML file is as follows.
<!DOCTYPE HTML>
<html manifest=“filename.appcache”> </html>

Q. What is the media type of appcache file?


ANSWER
A manifest file needs to have text/cache-manifest media type.
Q. What are the 3 different section of manifest file?
ANSWER
A manifest file has 3 different sections. These 3 different sections are as follows.
CACHE MANIFEST : Files listed under this header will be cached after they are
downloaded for the first time. NETWORK: Files listed under this header require a
connection to the server, and will never be cached. FALLBACK: Files listed under this
header specifies fallback pages if a page is inaccessible.
Q. What is NETWORK section?
ANSWER
NETWORK is one of the sections in manifest file. The file name
listed in the NETWORK section is never cached locally. The following code shows a
sample of NETWORK section.
NETWORK: login.html

Q. What is FALLBACK section?


ANSWER
FALLBACK is one of the sections in manifest file. In this section we
can mention the file name which will be called when application is offline. The following
code shows a sample of FALLBACK section.
FALLBACK:
/html/ /offline.html

Q. What is CACHE MANIFEST section?


ANSWER
CACHE MANIFEST is one of the sections in manifest file. The file names mentioned in
this section is cached locally. The following code shows a sample of CACHE MANIFEST
section.
/style.css
/favicon.gif /app.js

Q. How to view app cache detail in chrome browser?


ANSWER
We can view the app cache content like what it is caching, size and time etc. using the
following link in chrome browser.
chrome://appcache-internals/.
The following screenshot shows the appcache internal for my browser.

Q. How to detect the support of browser for appcache? ANSWER


We can detect the support of appcache by checking the existence of applicationCache in
window object. We can use javascript if statement which checks the truth value of
window.applicationCache object. The following screenshot shows the chrome console
detecting applicationCache object.
Q. How to update the appcache manually?
ANSWER
We can update the cache by doing hard reload to the browser. We can also call
swapCache() method to programmatically update the cache.
Chapter 16 Server Sent Events
Q. What is Server Side Events (SSE)?
ANSWER
HTML5 provides server side events feature by which a web page gets the update from the
server automatically. A great example of this feature is Facebook notification or Google +
updates.
Q. What is the content type of the server sent response? ANSWER
The content type of the server response is “text/event-stream” for the “Content-Type”
header.
Q. How to create an event source for listening to server updates? ANSWER
An event source can be created by instantiating the object of EventSource class with a
server path. The syntax for creating an event source is listed below.
var source = new EventSource(“<URL to Server>”);
Q. What are the event types is fired by an EventSource? ANSWER
An EventSource fires 3 different events. Callback methods can be attached to the source
for listening to these events. These event types are listed below.
onopen : This event is fired when the server open the connection to the browser.
onmessage: This event is fired when server produces the new output to the stream.
onerror: This event is fired when an error occurs by some means.
Q. How to close an event stream?
ANSWER
The event stream can be closed using close() method.
Q. What is the format of event stream?
ANSWER
The event stream is a simple stream of text data, which must be encoded using UTF-8.
Each message is separated by a pair of newline characters. A colon as the first character of
a line is, in essence, a comment, and is ignored.
Chapter 17 Miscellaneous Questions
Q. What is strict mode?
ANSWER
Strict mode is a new directive in new ECMA 5 JavaScript specification. It is used for
secure JavaScript coding. It eliminates some JavaScript silent errors by changing them to
throw errors.
The syntax of writing strict mode is below expression.
“use strict”
Below code shows the use of strict mode inside a function.
function sayHello(){
“use strict”;
myName = “Sandeep”;
}
sayHello();
The following screenshot shows the error produces by using an undeclared variable inside
the sayHello() method.

Q. List out some of the conditions that are not allowed in strict mode?
ANSWER
Find the list of the conditions that are not allowed in ECMA5 strict mode in below:
Using a variable without declaring is not allowed. Deleting a variable, a function, or an
argument is not allowed.
Defining a property more than once is not allowed. Duplicating a parameter name is not
allowed.
Octal numeric literals and escape characters are not allowed.
Writing to a read-only property is not allowed. Deleting an undeletable property is not
allowed.
The string “eval” cannot be used as a variable. The string “arguments” cannot be used as a
variable. The with statement is not allowed.
Future reserved keywords are not allowed.
Q. What is the output of 0.1+0.2 produces in the console and why? ANSWER
JavaScript math library follows IEEE 754 standards for math. IEEE 754 standards use 64
bit representation for a floating point number. This causes a problem while evaluating the
0.1 + 0.2 expression. Below screenshot shows the Firebug console for this expression.

JavaScript internally converts the 0.1 to 16 precision which becomes


0.1000000000000000 and then 0.2 gets added and becomes 0.30000000000000004.
Below screenshot shows this
demonstration in JavaScript code.

Q. How to resolve the issue 0.1+0.2 = 0.30000000000000004 and produce 0.1+0.2 = 03?
ANSWER
This issue can be resolved by using to toFixed(1) method to this expression. toFixed()
method converts a number to the specified decimal points. Below screenshot shows the
use of toFixed() method to produce the correct output which is 0.3.

Q. What will be the output of the below code and why?


(function(){
var a = b = 3;
})();
console.log(typeof a);
console.log(typeof b);
ANSWER
The above code will print undefined and Number in the console. Below screenshot shows
the output of the above code in the Firebug console.

JavaScript treats the above code as below screenshot. From the below code it is clear that
variable a is in local scope of the function and be is treated as this.b . The current
reference this represents the window object.

Q. What will be the output of the below code and why? console.log(1+2+4);
ANSWER
The output of the above code is 7 as the parameters are all
numbers. Below screenshot shows the output of the above code in
a chrome console.

Q. Explain Hoisting in JavaScript?


ANSWER
Hoisting is JavaScript’s default behavior of moving declarations to the top. In other words,
a variable can be used before it has been declared. Let’s understand hoisting using these
following examples.
Example 1:
The following code has a display() method which prints the value of a in the console.
function display(){ console.log(a);
}
display();

The output of the preceding code will be a reference error as we have not defined the
variable. The following screenshot shows the output of the preceding code.

Example 2:
The following code has a display() method which prints the value of a in the console.
function display(){
var a;
console.log(“Output: “+a);
}
display();

The output of the preceding code will be undefined as we have defined the variable but
not assigned any value. The following screenshot shows the output of the preceding code.

Example 3:
The following code has a display() method which prints the value of a in the console.
function display(){
console.log(“Output: “+a);
var a;
}
display();

The output of the preceding code will be undefined as we have defined the variable but
not assigned any value. Example 2 and Example 3 has same output. It means the variable
declaration is moved to the top. The following screenshot shows the output of the
preceding code.
About The Author

Sandeep Kumar Patel is a senior web developer and founder of www.tutorialsavvy.com, a


widely- read programming blog since 2012. He has more than five years of experience in
object-oriented JavaScript and JSON-based web applications development. He is GATE-
2005 Information Technology (IT) qualified and has a Master’s degree from VIT
University, Vellore.
You can know more about him from his
-LinkedIn profile (http://www.linkedin.com/in/techblogger).
-He has received the Dzone Most Valuable Blogger (MVB) award for technical
publications related to web technologies. His article can be viewed at
http://www.dzone.com/users/sandeepgiet.
-He has also received the Java Code Geek (JCG) badge for a technical article published in
JCG. His article can be viewed at http://www.javacodegeeks.com/author/sandeep-
kumar-patel/.
-Author of “Instant GSON” for Packt publication,
http://www.packtpub.com/create-json-data-java-objectsimplement-with-gson-
library/book
Questions or comments? E-mail me at
sandeeppateltech@gmail.com or find me on the following social networks:
-Facebook Page:
http://www.facebook.com/SandeepTechTutorials .
-Tutorial Blog: http://www.tutorialsavvy.com
One Last Thing…
When you turn the page, Kindle will give you the opportunity to rate this book and share
your thoughts on Facebook and Twitter. If you believe the book is worth sharing, please
would you take a few seconds to let your friends know about it? If it turns out to make a
difference in their professional lives, they’ll be forever grateful to you, as will I.
All the best,

Sandeep Kumar Patel.


Common JavaScript Developer Mistakes
1. Not Using const and let Properly:
Using var instead of const or let can lead to variable scope issues and unintended reassignments.
Failing to use const for variables that shouldn't be reassigned may result in accidental changes.
var counter = 0; // Should use "let" or "const" instead
const pi = 3.14;
pi = 3.1415; // Throws an error - constant cannot be reassigned

2. Incorrect Asynchronous Operations Handling:


Failing to handle asynchronous operations correctly can lead to timing-related bugs.
Not using async/await or .then() to handle asynchronous tasks can result in unexpected behavior.
// Incorrect asynchronous function handling
function getData() {
fetch('https://api.example.com/data')
.then(response => {
// Some data processing
});
// Code here executes before the data processing completes
}

3. Misunderstanding this :
Misusing this can cause unexpected behavior, especially in event handlers and callback functions.
Not binding this correctly in certain contexts may lead to errors or undefined values.
const button = document.querySelector('.btn');

button.addEventListener('click', function() {
// "this" does not refer to the button element here
this.classList.toggle('active'); // May not work as expected
});
4. Ignoring Error Handling:
Neglecting proper error handling can make it challenging to diagnose and fix issues.
Not using try/catch or .catch() to handle errors in asynchronous operations can lead to unhandled
rejections.
try {
// Some code that may throw an exception
} catch (error) {
// Missing proper error handling
}

5. Implicit Type Conversion:


Relying on implicit type conversion can lead to unexpected results and make the code harder to
understand.
It's essential to use explicit type conversion when necessary for clarity.
let total = 10 + '5'; // "105" (string concatenation) instead of 15 (addition)

6. Leaving Debugging Statements:


Leaving console.log or other debugging statements in the codebase can clutter the output and reduce
performance in production environments.
It's crucial to remove or comment out debugging statements before deployment.
function calculateTotal(price) {
console.log('Calculating total...'); // Leftover debugging statement
// Some code to calculate total
}

7. Not Handling Promises Rejection:


Not handling promise rejections can lead to unhandled promise rejections and potential application
crashes.
Always use .catch() to handle promise rejections.
fetchData()
.then(data => {
// Some data processing
})
// Missing ".catch()" to handle promise rejection
8. Using == Instead of === :
Using loose equality ( == ) instead of strict equality ( === ) can lead to unexpected type coercion
results.
Always use === to avoid issues with type comparisons.
5 == '5'; // true (loose equality)
5 === '5'; // false (strict equality)

9. Not Clearing Timers and Intervals:


Failing to clear timers and intervals can cause memory leaks and unnecessary resource consumption.
Always clear timers and intervals using clearTimeout and clearInterval when they are no longer
needed.
const timerId = setTimeout(() => {
// Some task
}, 5000);

clearTimeout(timerId); // Missing timer cleanup

10. Overusing Global Variables:


Overusing global variables can lead to naming conflicts and difficulty in maintaining the codebase.
Use local scope variables whenever possible to avoid global namespace pollution.
// Overuse of global variables
let count = 0;
function increment() {
count++;
}
I M P O RTA N T

JavaScript

concepts

FOR INTERVIEWS

Curated by tutort academy


1 New features in ES6 version.

The new features introduced in ES6 version of JavaScript


are:

Let and const keywords.

Arrow functions.

Multi-line Strings.

The destructuring assignment.

Enhanced object literals.

Promises.

Curated by tutort academy


2 Is javascript a statically typed or
a dynamically typed language?

JavaScript is a dynamically typed language. In a

dynamically typed language, the type of a variable is

checked during run-time in contrast to a statically

typed language, where the type of a variable is

checked during compile-time.

Static Typing Dynamic Typing

Variables have types Variables have no types

Variables cannot Variables can change type


change type

From To

10+ year

Sayan experience

Curated by tutort academy


3 Explain scope and scope chain
JavaScript

JavaScript has the following kinds of scopes:

Global Scope: A variable with global scope is one

that can be accessed from anywhere in the

application. It is the default scope for all code

running in script mode.

Example :

var x = 2;

console.log(x) //global scope

Local Scope: Any declared variable inside of a

function is referred to as having local scope. Within

a function, a local variable can be accessed. It

throws an error if you attempt to access any

variables specified inside a function from the

outside or another function.The scope for code

running in module mode.

Curated by tutort academy


Example :

// This part of code cannot use x

function myFunction() {

let x = 1;

// This part of code can use x

This part of code cannot use x

Function Scope: In JavaScript, every new function

results in the generation of a fresh scope. Variables

declared inside a function cannot be accessed

from outside the function or from another function.

When used inside of a function, var, let, and const

all act similarly. The scope created with a function.

Example :

function myFunction() {

const firstName = "Krishna"; // Function Scope

Scope Chain refers to the situation when one variable,

which may have a global, local, function, or block scope, is

used by another variable, function, or block, which may

also have a global, local, function, or block scope. This

entire chain construction continues till the user decides to

halt it in accordance with the need.

Curated by tutort academy


4 What are the differences between
var, const & let in JavaScript?

var let const

The scope of a var


The scope of a let The scope of a let
variable is functional
variable is block scope. variable is block scope.
scope.

It can be updated but It cannot be updated


It can be updated
cannot be re-declared or redeclared into the
and redeclared into
into the scope. scope.
the scope.

It can be declared It can be declared It cannot be declared


without initialization. without initialization. without initialization.

It can be accessed It cannot be accessed

It cannot be accessed without


without initialization without initialization, as
initialization otherwise it will
as its default value is it cannot be declared
give ‘referenceError’.
“undefined”. without initialization.

Hoisting is done, but not


Hoisting is done, but not initialized (this is the
Hoisting done, with initialized (this is the reason reason for the error
initializing as ‘default’ for the error when we access when we access the
value the let variable before
const variable before

declaration/initialization declaration/
initialization

Curated by tutort academy


5 What is hoisting in JavaScript?

Hoisting is the default behaviour of javascript where all


the variable and function declarations are moved on top.

Declaration
a=1:

Move on top alert(a=’+a);

var a;

This means that irrespective of where the variables and


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

Curated by tutort academy


6 Explain temporal dead zone.

Temporal Dead Zone is a behaviour that occurs with

variables declared using let and const keywords. It is

a behaviour where we try to access a variable before

it is initialized.

Examples of temporal dead zone:

num = 23; // Gives reference error

let num;

function func(){

greeting = "Hi"; // Throws a reference error

let greeting;

func();

Curated by tutort academy


7 What is closure in JavaScript?

A closure consists of references to the surrounding

state (the lexical environment) and a function that

has been wrapped (contained). In other words, a

closure enables inner functions to access the scope

of an outside function. Closures are formed whenever

a function is created in JavaScript, during function

creation time.

8 What are differences between “==”


& “===”?

The == operator performs a loose equality comparison

that, if necessary to enable the comparison, applies

type coercion.

On the other hand, the === operator conducts a strict

equality comparison without type coercion and

necessitates that the operands be of the same type

(as well as the same value).

Curated by tutort academy


9 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

For E.g.:

Math.sqrt(-1);

parseInt("Hello");

Courses Offered by Tutort Academy

DSA with System Full Stack with


Design MERN

Learn more Learn more

Curated by tutort academy


10 What is the difference between
null and undefined?

null undefined

It is an assignment value which It is not an assignment value where


indicates that variable points to a variable has been declared but
no object. has not yet been assigned a value.

Type of null is object Type of undefined is undefined

The null value is a primitive value The undefined value is a primitive


that represents the null, empty, or value used when a variable has
non-existent reference. not been assigned a value.

Indicates the absence of a


Indicates absence of variable itself
value for a variable

Converted to zero (0) while Converted to NaN while


performing primitive operations performing primitive operations

Curated by tutort academy


11 What are the terms BOM and DOM in
JavaScript?

DOM stands for Document Object Model and BOM for

Browser Object Model.

DOM: An element may be added, changed, or removed

from a document using the Document Object Model

(DOM), a programming interface for HTML and XML

documents. It specifies how a document is accessed

and handled, as well as its logical structure. The DOM

allows the webpage to be represented as a structured

hierarchy, making it simple to access and modify HTML

tags, IDs, classes, attributes, and elements using the

Document object's provided commands and methods.

This makes it easier for programmers and users to

understand the document.

DOM provides several methods to find & manipulate the

behavior of the HTML element:

getElementById() Method

getElementsByClassName() Method

getElementsByName() Method

getElementsByTagName() Method

querySelector() Method

querySelectorAll() Method

Curated by tutort academy


BOM: Browser Object Model (BOM) is a browser-specific

convention referring to all the objects exposed by the

web browser. The BOM allows JavaScript to “interact

with” the browser. The window object represents a

browser window and all its corresponding features. A

window object is created automatically by the browser

itself. JavaScript’s window.screen object contains

information about the user’s screen.

Window properties of BOM are:

screen.width

screen.height

screen.availWidth

screen.availHeight

screen.colorDepth

screen.pixelDepth

Window methods of BOM are:

window.open() Method

window.close() Method

window.moveTo() Method

window moveBy() Method

window.resizeTo() Method

Curated by tutort academy


12 What is Critical Rendering Path?

The Critical Rendering Path is the sequence of

steps the browser goes through to convert the

HTML, CSS, and JavaScript into pixels on the screen.

Optimizing the critical render path improves render

performance. The critical rendering path includes

the Document Object Model (DOM), CSS Object

Model (CSSOM), render tree and layout.

Tutort Benefits

1:1 Mentorship from


24x7 Live 1:1 Video based

Industry experts doubt support

Special support for


Resume building & Mock

foreign students Interview Preparations

Curated by tutort academy


13 What are basic JavaScript array
methods?

Some of the basic JavaScript methods are:

push() method: adding a new element to an array.

Since JavaScript arrays are changeable objects,

adding and removing elements from an array is

simple. Additionally, it alters itself when we change

the array's elements.

Syntax: Array.push(item1, item2 …)

pop() method: This method is used to remove

elements from the end of an array.

Syntax: Array.pop()

Curated by tutort academy


slice() method: This method returns a new array

containing a portion of the original array, based on

the start and end index provided as arguments

Syntax: Array.slice (startIndex , endIndex);

map() method: The map() method in JavaScript

creates an array by calling a specific function on

each element present in the parent array. It is a non-

mutating method. Generally, the map() method is

used to iterate over an array and call the function on

every element of an array.

Syntax: Array.map(function(currentValue,

index, arr), thisValue)

reduce() method: The array reduce() method in

JavaScript is used to reduce the array to a single

value and executes a provided function for each

value of the array (from left to right) and the return

value of the function is stored in an accumulator.

Syntax: Array.reduce(function(total,

currentValue, currentIndex, arr), initialValue)

Curated by tutort academy


14 What is the rest parameter and
spread operator?

Rest parameter ( … ):

It offers a better method of managing a function's

parameters.

We can write functions that accept a variable

number of arguments using the rest parameter

syntax.

The remainder parameter will turn any number of

inputs into an array.

Additionally, it assists in extracting all or some of

the arguments.

Applying three dots (...) before the parameters

enables the use of rest parameters.

Curated by tutort academy


Syntax:

function extractingArgs(...args){

return args[1];

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

function addAllArgs(...args){

let sumOfArgs = 0;

let i = 0;

while(i < args.length){

sumOfArgs += args[i];

i++;

return sumOfArgs;

addAllArgs(6, 5, 7, 99); // Returns 117

addAllArgs(1, 3, 4); // Returns 8

Note- Rest parameter should always be used at the

last parameter of a function.

Curated by tutort academy


Spread operator(…): Although the spread operator's syntax

is identical to that of the rest parameter, it is used to spread

object literals and arrays. Spread operators are also used

when a function call expects one or more arguments.

Syntax:

function addFourNumbers(num1,num2,num3,num4){

return num1 + num2 + num3 + num4;

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

addFourNumbers(...fourNumbers);

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

let array1 = [3, 4, 5, 6];

let clonedArray1 = [...array1];

// Spreads the array into 3,4,5,6

console.log(clonedArray1); // Outputs [3,4,5,6]

let obj1 = {x:'Hello', y:'Bye'};

let clonedObj1 = {...obj1}; // Spreads and clones obj1

console.log(obj1);

let obj2 = {z:'Yes', a:'No'};

let mergedObj = {...obj1, ...obj2}; // Spreads both the

objects and merges it

console.log(mergedObj);

// Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'};

Curated by tutort academy


15 Explain this keyword

In JavaScript, the this keyword always refers to an

object. The thing about it is that the object it refers to

will vary depending on how and where this is being

called. If we call this by itself, meaning not within a

function, object, or whatever, it will refer to the global

window object. The majority of the time, the value of

this depends on the runtime binding used to call a

function. It may change every time the function is

called and cannot be changed by assignment while

the function is being executed. Although arrow

functions don't give their own this binding (it keeps

the this value of the enclosing lexical context), the

bind() method can set the value of a function's this

regardless of how it's called

From To

10+ year

Sayan experience

Curated by tutort academy


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

We use call, bind and apply methods to set the this

keyword independent of how the function is called. This is

especially useful for the callbacks.Every function object is

also given a few unique methods and attributes by

JavaScript. These are the methods that every JavaScript

function inherits. Every function inherits certain methods,

such as call, bind, and apply.

bind(): The bind method creates a new function and sets

the this keyword to the specified object.

Syntax:

function.bind(thisArg, optionalArguments)

From To With

10+ year

Mohit Jain experience

Curated by tutort academy


For example:

Let’s suppose we have two person objects.

const john = {

name: 'John',

age: 24,

};

const jane = {

name: 'Jane',

age: 22,

};

Let’s add a greeting function:

function greeting() {

console.log(`Hi, I am ${this.name} and I am

${this.age} years old`);

Curated by tutort academy


We can use the bind method on the greeting function to

bind the this keyword to john and jane objects.

For example:

const greetingJohn = greeting.bind(john);

// Hi, I am John and I am 24 years old

greetingJohn();

const greetingJane = greeting.bind(jane);

// Hi, I am Jane and I am 22 years old

greetingJane();

Here greeting.bind(john) creates a new function with this

set to john object, which we then assign to greetingJohn

variable. Similarly for greetingJane.

call(): The call method initializes the this inside the

function and launches it right away.

In contrast to bind(), which produces a copy of the

function and sets the this keyword, call() sets the this

keyword, executes the function instantly, and does not

create a new copy of the function.

Curated by tutort academy


Syntax: function.call(thisArg, arg1, agr2, ...)

For example:

function greeting() {

console.log(`Hi, I am ${this.name} and I am

${this.age} years old`);

const john = {

name: 'John',

age: 24,

};

const jane = {

name: 'Jane',

age: 22,

};

// Hi, I am John and I am 24 years old

greeting.call(john);

// Hi, I am Jane and I am 22 years old

greeting.call(jane);

Above example is similar to the bind() example except that

call() does not create a new function. We are directly setting the

this keyword using call().

Curated by tutort academy


apply(): The apply() method is similar to call(). The

difference is that the apply() method accepts an array

of arguments instead of comma separated values.

Syntax: function.apply(thisArg, [argumentsArr])

For example:

function greet(greeting, lang) {

console.log(lang);

console.log(`${greeting}, I am ${this.name}

and I am ${this.age} years old`);

const john = {

name: 'John',

age: 24,

};

const jane = {

name: 'Jane',

age: 22,

};

// Hi, I am John and I am 24 years old

greet.apply(john, ['Hi', 'en']);

// Hi, I am Jane and I am 22 years old

greet.apply(jane, ['Hola', 'es']);

Curated by tutort academy


Is JavaScript single-threaded, if yes then how
17
it works as an multi-threaded language? OR
What is event loop in javascript?

JavaScript is a single-threaded asynchronous

programming language. But what does it mean? What

is this event loop in JavaScript that we all keep talking

about? To know more click here

Courses Offered by Tutort Academy

DSA with System Full Stack with


Design MERN

Learn more Learn more

Curated by tutort academy


18 What are promises, async-await
and callback?

A Promise is a proxy for a value not necessarily known

when the promise is created. It allows you to

associate handlers with an asynchronous action's

eventual success value or failure reason.

This lets asynchronous methods return values like

synchronous methods: instead of immediately

returning the final value, the asynchronous method

returns a promise to supply the value at some point

in the future.

Curated by tutort academy


A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation was completed


successfully.

rejected: meaning that the operation failed.

A promise is said to be settled if it is either fulfilled or


rejected, but not pending.

Async simply allows us to write promises-based

code as if it was synchronous and it checks that we

are not breaking the execution thread. It operates

asynchronously via the event loop. Async functions

will always return a value. It makes sure that a

promise is returned and if it is not returned then

JavaScript automatically wraps it in a promise

which is resolved with its value.

Syntax:

const func1 = async() => {

return “Hello World!”;

Curated by tutort academy


Await function is used to wait for the promise. It

could be used within the async block only. It makes

the code wait until the promise returns a result. It

only makes the async block wait.

Syntax:

const func2 = async () = {

let x= await func1();

console.log(x);

Tutort Provides 24x7 Live 1:1 Video based doubt support

Curated by tutort academy


19 What is 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,

Syntax:

async1(function(){

async2(function(){

async3(function(){

async4(function(){

....

});

});

});

});

Curated by tutort academy


20 What are observables?

Observables in JavaScript are a way to handle

asynchronous events. They are functions that return a

stream of values, which can be used to represent data

streams such as DOM events, mouse events, or HTTP

requests.

Observables work by providing a way to subscribe to a

stream of values, and then receiving those values as they

become available. This allows you to respond to events in

a more reactive way, without having to wait for the entire

event stream to complete before processing it.

To use observables in JavaScript, you can use the RxJS

library.

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {

subscriber.next(1);

subscriber.next(2);

subscriber.next(3);

subscriber.complete();

});

observable.subscribe(value => {

console.log(value);

});

Curated by tutort academy


21 What are the differences between
promises and observables?

Promises Observables

Emits multiple values over a


Emits only a single value at
period of time(stream of values
a time
ranging from 0 to multiple)

Eager in nature; they are going Lazy in nature; they require


to be called immediately subscription to be invoked

Promise is always
Observable can be either
asynchronous even though it
synchronous or asynchronous
resolved immediately

Provides operators such as


Doesn't provide any
map, forEach, filter, reduce,
operators
retry, and retryWhen etc

Cancelled by using
Cannot be cancelled
unsubscribe() method

Curated by tutort academy


21 What is the difference between
setTimeout, setImmediate and
process.nextTick?

setTimeout(): Using the setTimeout() method, a

callback function can be scheduled to run once after a

millisecond delay.

setImmediate(): Use the setImmediate function to run

a function immediately following the conclusion of the

current event loop.

process.nextTick(): If process.nextTick() is invoked in a

given phase, all the callbacks passed to

process.nextTick() will be resolved before the event

loop continues. This will block the event loop and create

I/O Starvation if process.nextTick() is called recursively.

From To Switch from

Service Based
Uzeen
Chhabra Company

Curated by tutort academy


23 What is microtask in JavaScript?

A microtask is a short function which is executed

after the function or program which created it exits

and only if the JavaScript execution stack is empty,

but before returning control to the event loop being

used by the user agent to drive the script's

execution environment.

24 What Pure Functions in JavaScript?

A function or section of code that always yields the same

outcome when the same arguments are supplied is

known as a pure function. It is independent of any state or

data changes that occur while a program is running.

Instead, it just relies on the arguments it is given.

Additionally, a pure function does not result in any side

effects that can be seen, such as network queries, data

alteration, etc.

Curated by tutort academy


25 What is an error object and its
different error name object?

When an error happens, an error object—a built-in error

object—provides error information. There are two

attributes: name and message. For instance, the following

function records error information,

Syntax:

try {

greeting("Welcome");

} catch (err) {

console.log(err.name + "<br>" + err.message);

There are 6 different types of error names returned from error object,

Error name Description

An error has occurred in the


EvalError
eval() function

An error has occurred with a


RangeError
number "out of range"

ReferenceError An error due to an illegal reference

SyntaxError An error due to syntax

TypeError An error due to a type error

URIError An error due to encodeURI()

Curated by tutort academy


26 What are the various statements in
error handling?

Below are the list of statements used in an error handling,

try: This statement is used to test a block of code for errors

catch: This statement is used to handle the error

throw: This statement is used to create custom errors.

finally: This statement is used to execute code after try and

catch regardless of the result.

Why Tutort Academy?

Guaranteed
Hiring
Highest

100% Job Referrals 250+ Partners 2.1CR CTC

Curated by tutort academy


27 What do you mean by strict mode in
javascript and characteristics of
javascript strict-mode?

In ECMAScript 5, a new feature called JavaScript Strict

Mode allows you to write a code or a function in a "strict"

operational environment. When it comes to throwing

errors, javascript is often 'not extremely severe'. However,

in "Strict mode," all errors, even silent faults, will result in a

throw. Debugging hence becomes more easier. Thus, the

chance of a coder committing a mistake is decreased.

Characteristics of strict mode in javascript:

Duplicate arguments are not allowed by developers.

Use of javascript’s keyword as parameter or

function name is not allowed.

The 'use strict' keyword is used to define strict

mode at the start of the script. Strict mode is

supported by all browsers

Creating of global variables is not allowed.

Curated by tutort academy


28 What are the differences between
cookie, local storage and session
storage?

Cookie Local storage Session

Can be accessed on
Can be accessed on Can be accessed on
both server- side &
client- side only client- side only
client side

Lifetime is until deleted Lifetime is until tab is


As configured using
closed
expires option

SSL is supported SSL is not supported SSL is not supported

Maximum size is 4 Maximum size is 5 MB


Maximum size is 5 MB
KB

From To
Placed with

Subhadip 100% Hike


Chowdhury

Curated by tutort academy


29 Explain 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.

I got rejected in the Amazon interview. After that, I joined Tutort Academy
for DSA concepts as a working professional. They fulfilled my all
requirements and that is why I am in Microsoft right now. I highly
recommend Tutort Academy for professionals.
Nikesh Bisen

Curated by tutort academy


30 What are generators and what are
its different kinds?

Introduced in the ES6 version, generator functions are a special

class of functions.

They can be stopped midway and then continue from where

they had stopped.

Generator functions are declared with the function* keyword

instead of the normal function keyword.

There are five kinds of generators,

Generator function declaration

Generator function expressions

Generator method definitions in object literals

Generator method definitions in class

Generator as a computed property

Curated by tutort academy


31 Difference between Debouncing and
Throttling.

Debouncing Throttling

Debouncing waits for a certain An error has occurred in the


time before invoking the function eval() function
again.

Ensures that the function is called


An error has occurred with a
only once, even if the event is
number "out of range"
triggered multiple times.

Useful when you want to delay the


invocation of a function until a certain An error due to an illegal reference
period of inactivity has passed.

Eg. You can debounce an async API


request function that is called every An error due to syntax

time the user types in an input field.

Syntax:
Syntax:

function debounce(func, delay) {


function throttle(callback, delay =
let timerId;
1000) {

return function () {
let shouldWait = false;

const context = this;


return (...args) => {

const args = arguments;


if (shouldWait) return;

clearTimeout(timerId);
callback(...args);

timerId = setTimeout(function () {
shouldWait = true;

func.apply(context, args);
setTimeout(() => {

}, delay);
shouldWait = false;

};
}, delay);

} };

Curated by tutort academy


Start Your
Upskilling with us

Explore More

www.tutort.net

Watch us on Youtube Read more on Quora

Explore our courses

Advanced DSA & System Full Stack Specialisation in

Design Course Software Development

Follow us on
Ziad Eleraky
1. Get current date and time:

2. Check if a variable is an array:

3. Merge two arrays:

4. Remove duplicates from an array:


5. Sort an array in ascending order:

6. Reverse an array:

7. Convert string to number:

8. Generate a random number


between two values:
9. Check if a string contains a substring:

10. Get the length of an object:

11. Convert object to array:

12. Check if an object is empty:


13. Get current URL:

14. Redirect to a new URL:

15. Set a cookie:

16. Get a cookie:

17. Check if a cookie exists:


18. Remove a cookie:

19. Get the current viewport dimensions:

20. Copy text to clipboard:


Happy
Coding ;)
/in/ziad-eleraky/

Resource:
https://www.javacodegeeks.com/2023/05/20-best-javascript-snippets.html

You might also like