Quick JavaScript Interview Questions - Sandeep Patel
Quick JavaScript Interview Questions - Sandeep 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 :
Lets 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.
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.
console.log(typeOfAllNumber)
Below screenshot shows output of the above code Firebug console.
The following screenshot shows the new overridden definition of split () method. It is now
normally returns string I am overriden.
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.
}
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.
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
Except IE, the other browser added by addEventListener() method. Below screenshot
shows the demonstration this method in Firebug.
The following screenshot shows removing click event handler from document for Firefox
browser.
Chapter 3 Closure
Q. What is Closure?
ANSWER
A closure is an inner function that has access to the outer wrapped functions variables. It
has three different scope accesses:- Self-scope:
It has access to properties present in its own scope.
Wrapped functions 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.
<!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.
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, its pretty much stuck there. Theres 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.
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.
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.
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.
<!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.
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. 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.
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.
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
Lets 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 output of the preceding code shown in following screenshot with hour, minute and
second is displayed from the worker response messages.
});
</ 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.
<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.
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.
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.
<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.
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 objects 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.
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.
(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 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.