Professional Documents
Culture Documents
Js Great Read
Js Great Read
JavaScript
JavaScript
Concepts for Interviews
*Disclaimer*
Everyone learns uniquely.
include:
value.
following ways:
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:
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
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.
// Define an object
let obj1 = {
value: 42,
valueOfThis: function() {
};
console.log(obj1.valueOfThis()); // Output: 42
Arrow Function:
Javascript
let obj2 = {
value: 84,
valueOfThis: () => {
this case)
};
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
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
Javascript
function performTask() {
var result;
performTask();
Hoisting also occurs within local scopes, like functions. Here, result
Key Points:
function strict_function() {
'use strict';
x = 'Test message';
console.log(x);
Javascript
function createMultiplier(factor) {
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() {
};
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() {
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() {
exampleFunction();
function exampleFunction() {
exampleFunction();
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
function mainFunction(){
innerFunction1();
innerFunction2();
mainFunction();
MEDIUM
function outerFunction() {
function innerFunction() {
let innerVariable = 5;
return innerFunction;
closureFunction();
MEDIUM
outerFunction defines an outer variable (outerVariable) and an
inner function (innerFunction).
function sayHello(greeting) {
function sayHello(greeting) {
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) {
Javascript
let total = 0;
function addToTotal(value) {
total += value;
addToTotal(5);
console.log(total); // Output: 5
this.name = name;
Person.prototype.greet = function() {
};
MEDIUM
Javascript
Javascript
function customGreeting(name) {
function outerFunction(callback) {
callback(name);
outerFunction(customGreeting);
Javascript
getUser(function(user) {
getProfile(user.id, function(profile) {
getPosts(user.id, function(posts) {
});
});
});
});
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.
var value1 = 1;
let value2 = 2;
Javascript
});
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
// code here
// 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.
yield 1;
yield 2;
yield 3;
} // Creating a generator
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).
return a + b;
Example:
Javascript
return a + b;
};
hoisted in the same way. If you try to call a function expression before
function.
HARD
What is the difference between setTimeout,
Q.25 setImmediate and process.nextTick?
}, 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(() => {
});
: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(() => {
});
Why
Bosscoder?
750+ Alumni placed at Top
Product-based companies.
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.
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.
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
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 .
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 .
These errors will be caught in the catch blocks as e and then assigned
to the variables e1 and e2 .
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 .
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.
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.
It may seem that if we set the delay to 0 , then the function will be
executed immediately, but it’s not the case.
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.
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
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.
In our case, it’s called without any arguments which is a special case.
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.
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.
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:
When we try to sum two arrays using the + operator, the arrays are
first converted to strings and then these strings are concatenated.
In this case, empty string and false are considered equal and the
condition of the if statement will be evaluated to true .
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.
So, if the rejection does take place, then we’ll likely see a message like
UnhandledPromiseRejectionWarning … or something along these
lines.
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.
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.
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.
When we’re slicing this string with slice(0, 4) we’ll get the first four
characters, which represent the year.
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.
[ 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 .
console.log(arr); // [ 1, 4, 5 ]
console.log(splicedArr); // [ 2, 3 ]
arr.splice(1, 2, ...splicedArr);
console.log(arr);
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.
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
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 .
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.
So, after the first 2 lines of code, we’ll get the following state:
[ 1, 2, 3, 4, 5] // arr
[ 2 ] // slicedArr
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:
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.
If your first guess was that Math.max() should return some big
number that’s for sure bigger than 0 , then you’re wrong.
But that’s only before we get into the details of how the numbers are
represented in JavaScript.
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.
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.
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.
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.
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.
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 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)
5
Better code
Improved code
Correct way
6
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
much clear from the names of the properties. Also, the
order of properties doesn’t matter anymore.
20
Object destructuring on arrays
21
Skip values in array destructuring
22
Format the output of JSON.stringify
23
Filter with JSON.stringify
24
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
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
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
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
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’}
The following screenshot shows the new overridden definition of split () method. It is now
normally returns string “I am overriden”.
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. 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.
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.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?”); 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.
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.
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,
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.
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.
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. 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.
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.
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.
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
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
}
JavaScript
concepts
FOR INTERVIEWS
Arrow functions.
Multi-line Strings.
Promises.
From To
10+ year
Sayan experience
Example :
var x = 2;
function myFunction() {
let x = 1;
Example :
function myFunction() {
declaration/initialization declaration/
initialization
Declaration
a=1:
var a;
it is initialized.
let num;
function func(){
let greeting;
func();
creation time.
type coercion.
cases
For E.g.:
Math.sqrt(-1);
parseInt("Hello");
null undefined
getElementById() Method
getElementsByClassName() Method
getElementsByName() Method
getElementsByTagName() Method
querySelector() Method
querySelectorAll() Method
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
window.open() Method
window.close() Method
window.moveTo() Method
window.resizeTo() Method
Tutort Benefits
Syntax: Array.pop()
Syntax: Array.map(function(currentValue,
Syntax: Array.reduce(function(total,
Rest parameter ( … ):
parameters.
syntax.
the arguments.
function extractingArgs(...args){
return args[1];
// extractingArgs(8,9,1); // Returns 9
function addAllArgs(...args){
let sumOfArgs = 0;
let i = 0;
sumOfArgs += args[i];
i++;
return sumOfArgs;
Syntax:
function addFourNumbers(num1,num2,num3,num4){
addFourNumbers(...fourNumbers);
console.log(obj1);
console.log(mergedObj);
From To
10+ year
Sayan experience
Syntax:
function.bind(thisArg, optionalArguments)
From To With
10+ year
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
function greeting() {
For example:
greetingJohn();
greetingJane();
function and sets the this keyword, call() sets the this
For example:
function greeting() {
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
greeting.call(john);
greeting.call(jane);
call() does not create a new function. We are directly setting the
For example:
console.log(lang);
console.log(`${greeting}, I am ${this.name}
const john = {
name: 'John',
age: 24,
};
const jane = {
name: 'Jane',
age: 22,
};
in the future.
Syntax:
Syntax:
console.log(x);
Syntax:
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
requests.
library.
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.complete();
});
observable.subscribe(value => {
console.log(value);
});
Promises Observables
Promise is always
Observable can be either
asynchronous even though it
synchronous or asynchronous
resolved immediately
Cancelled by using
Cannot be cancelled
unsubscribe() method
millisecond delay.
loop continues. This will block the event loop and create
Service Based
Uzeen
Chhabra Company
execution environment.
alteration, etc.
Syntax:
try {
greeting("Welcome");
} catch (err) {
There are 6 different types of error names returned from error object,
Guaranteed
Hiring
Highest
Can be accessed on
Can be accessed on Can be accessed on
both server- side &
client- side only client- side only
client side
From To
Placed with
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
class of functions.
Debouncing Throttling
Syntax:
Syntax:
return function () {
let shouldWait = false;
clearTimeout(timerId);
callback(...args);
timerId = setTimeout(function () {
shouldWait = true;
func.apply(context, args);
setTimeout(() => {
}, delay);
shouldWait = false;
};
}, delay);
} };
Explore More
www.tutort.net
Follow us on
Ziad Eleraky
1. Get current date and time:
6. Reverse an array:
Resource:
https://www.javacodegeeks.com/2023/05/20-best-javascript-snippets.html