0% found this document useful (0 votes)
16K views

65 JavaScript Interview Questions and Answers - The ULTIMATE List (PDF Download) - Web Code Geeks - 2016

Uploaded by

Suyash Vaidya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16K views

65 JavaScript Interview Questions and Answers - The ULTIMATE List (PDF Download) - Web Code Geeks - 2016

Uploaded by

Suyash Vaidya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

Knowledge Base Resources Job Board Join Us About      è Search...

Learn Web Design & Coding
Treehouse
Learn how to build apps & websites.
learning for free today!

ASP.NET CLOUD CSS DEVOPS HTML5 JAVASCRIPT NOSQL PHP PYTHON RUBY WEB DEV WEB SERVERS WORDPRESS

⌂ Home » JavaScript » 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download)

ABOUT FABIO CIMO

Fabio is a passionate student in web tehnologies including front­end (HTML/CSS) and web design. He likes exploring as much as
possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the
same time he works as a freelancer on both web programming and graphic design.

         

65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF


Download) Treehouse

 Posted by: Fabio Cimo   in JavaScript   December 30th, 2015

Have you wondered what are the most common Javascript questions developers are
asked in interviews? Well, in this article we’re going to go through some of the most
anticipated questions (and their answers) to help you get going in job interviews and
make a good impression with your knowledge.

JavaScript developers are in high demand in the IT world. If this is the role that best
expresses your knowledge and professionalism, you have a lot of opportunities to Learn Web Design & Coding
change the company you work for and increase your salary. Learn how to build apps & websites. Start le
for free today!
But before you are hired by a company, you have to demonstrate your skills in order to
pass the interview process.
NEWSLETTER

JavaScript Interview Coming Up?
37,119 insiders are already enjoying
Subscribe to our newsletter weekly updates and complimentary
and download the Ultimate whitepapers!
JavaScript interview Join them now to gain 
questions and answers access to the latest news in the Web
collection right now! developers world, as well as insights ab
HTML5, CSS, JavaScript, WordPress and
In order to get you prepared for your related technologies.
next JavaScript interview, we have
compiled a huge list of relevant Email address:
questions and their respective
answers. Besides studying them Your email address
online you may download the eBook
in PDF format!
  Sign up

Email address:
Your email address
JOIN US
Sign up
With  1,240,600  monthly unique visitors a
500  authors we 
Table Of Contents placed among the 
resources and dev
1. Javascript: An Overview sites around. Cons
1.1 What is Javascript? being on the looko
1.2 Javascript Code Implementation partners; we enco
you to join us. So 
1.3 Javascript Events
have a blog with u
2. Theoretical Questions and interesting con
3. Code Output Questions you should check o
4. Write Code Questions WCG partners program. You can also be a
4.1 Functional Javascript writer for Web Code Geeks and hone you
skills!
4.2 Dynamic Objects
4.3 Binding Shim
4.4 Animation
4.5 Memorization

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 1/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
5. Rapid Fire – Tricky Questions
6. 10 Essential Questions
6.1 Hoisting
7. General Questions 36% OFF 37% OFF
8. A Final Note

1. Javascript: An Overview
1.1 What is Javascript?
Micromax Canvas A1
JavaScript is a high­level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language
specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web content production; the majority of
27% OFF
websites employ it and it is supported by all modern web browsers without plug­ins or any kind of other extension.

Redmi 2

35% OFF 36% OFF

HTC Desire 620
Micromax Unite 3

CAREER OPPORTUNITIES

HTML 5 DeveloperCognizant
Philadelphia, PA
Jul, 13
Junior DeveloperLaunchCode
Miami, FL
Aug, 04
Junior DeveloperLaunchCode
Fort Lauderdale, FL
Jul, 30
Junior DeveloperLaunchCode
Providence, RI
Aug, 04
Website Developer 1Lockheed Martin
Marietta, GA
Jul, 09
HTML, CSS & Javascript are the three most basic languages to create web content! Junior DeveloperLaunchCode
St. Louis, MO
Jul, 30
JavaScript is prototype­based with first­class functions, making it a multi­paradigm language, supporting object­oriented, imperative, and Junior DeveloperEndurance Internation
functional programming styles. It has an API for working with text, arrays, dates and regular expressions, but does not include any I/O, such Austin, TX
as networking, storage or graphics facilities, relying for these upon the host environment in which it is embedded. Jul, 23
Junior DeveloperPierry Software Inc
So, to conclude this paragraph, keep in mind answers to the question “What is Javascript?” Redwood City, CA
Jul, 22
• It is a programming language. Junior DeveloperLaunchCode
• It is an interpreted language. Honolulu, HI
Jul, 23
• It is object­based programming.
Performance Testing LeadDiverse Lynx
• It is widely used and supported Minneapolis, MN
• It is accessible to the beginner. Apr, 15
1 2 ... 4110 »

1.2 Javascript Code Implementation
Keyword ...
Implementing Javascript
Location ...
There are three ways to add JavaScript commands to your Web Pages:
Country ...
• Embedding code
• Inline code
• External file Filter Results
jobs by 

Writing Javascript
JavaScript code is typically embedded in the HTML, to be interpreted and run by the client’s browser. Here are some tips to remember when
writing JavaScript commands.

• JavaScript code is case sensitive
• White space between words and tabs are ignored
• Line breaks are ignored except within a statement
• JavaScript statements end with a semi­colon: ‘;’

Objects
https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 2/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
Objects
JavaScript supports programming with objects. Objects are a way of organizing the variables. The different screen elements such as Web
pages, forms, text boxes, images, and buttons are treated as objects. Every object has its own properties and methods.

• Properties define the characteristics of an object.
Examples: color, length, name, height, width
• Methods are the actions that the object can perform or that can be performed on the object.
Examples: alert, confirm, write, open, close .

The Javascript Object Hierarchy

1.3 Javascript Events
The objects in a Web page are organized in a hierarchy. All objects have properties and methods. In addition, some objects also have
“events”. Events are things that happen, usually user actions, that are associated with an object. The “event handler” is a command that is
used to specify actions in response to an event. Common events are:


onLoad

– occurs when a page loads in a browser

onUnload

– occurs just before the user exits a page

onMouseOver

– occurs when you point to an object

onMouseOut

– occurs when you point away from an object

onSubmit

– occurs when you submit a form

onClick

– occurs when an object is clicked

JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page
loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc.

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 3/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to
users, data to be validated, and virtually any other type of response imaginable. Events are a part of the Document Object Model (DOM) Level
3 and every HTML element contains a set of events which can trigger JavaScript Code.

2. Theoretical Questions
1. Can you name two programming paradigms important for JavaScript app developers?
JavaScript is a multi­paradigm language, supporting imperative/procedural programming along with OOP (Object­Oriented Programming)
and functional programming. JavaScript supports OOP with prototypal inheritance.

2. What is functional programming?
Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data. Lisp (specified in
1958) was among the first languages to support functional programming, and was heavily inspired by lambda calculus. Functional
programming is an essential concept in JavaScript (one of the two pillars of JavaScript). Several common functional utilities were added to
JavaScript in ES5.

Focus is on:
1. Function purity
2. Avoiding side­effects
3. Simple function composition

3. What is the difference between classical inheritance and prototypal inheritance?
Class Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub­class relationships:
hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the `new` keyword. Class inheritance may or
may not use the `class` keyword from ES6.

Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or
Object.create()

. Instances may be composed from many different objects, allowing for easy selective inheritance.

4. When is prototypal inheritance an appropriate choice?
There is more than one type of prototypal inheritance:

• Delegation (i.e., the prototype chain).
• Concatenative (i.e. mixins,
Object.assign()

).
• Functional (Not to be confused with functional programming. A function used to create a closure for private state/encapsulation).

Each type of prototypal inheritance has its own set of use­cases, but all of them are equally useful in their ability to enable composition,
which creates has­a or uses­a or can­do relationships as opposed to the is­a relationship created with class inheritance.

5. What is asynchronous programming, and why is it important in JavaScript?
Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top­to­bottom, blocking on
long­running tasks such as network requests and disk I/O.

Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and
the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be
run, where the control flow continues. In this way, a single program thread can handle many concurrent operations.

User interfaces are asynchronous by nature, and spend most of their time waiting for user input to interrupt the event loop and trigger event
handlers. Node is asynchronous by default, meaning that the server works in much the same way, waiting in a loop for a network request, and
accepting more incoming requests while the first one is being handled.

This is important in JavaScript, because it is a very natural fit for user interface code, and very beneficial to performance on the server.

6. What are JavaScript data types?
In JavaScript, there are three primary data types, two composite data types, and two special data types.

Primary Data Types

• String
• Number
• Boolean

Composite Data Types

• Object
• Array

Special Data Types

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 4/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
• Null
• Undefined

7. What is the difference between “==” and “===”?
“==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two
variables are different. So, the second option needs both the value and the type to be the same for the operands.

8. What is an undefined value in JavaScript?
Undefined value means the:

• Variable used in the code doesn’t exist
• Variable is not assigned to any value
• Property doesn’t exist

9. What are the different types of errors in JavaScript?
There are three types of errors:

• Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it
generates the errors dynamically.
• Run time errors: Errors that come due to misuse of the command inside the HTML language.
• Logical Errors: These are errors that occur due to the wrong logic performed on a function.

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

11. What is the significance, and what are the benefits, of including ‘use strict’ at the beginning
of a JavaScript source file?
use strict

is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have
been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.

Some of the key benefits of strict mode include:

• Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or
throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.

• Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with
that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.

• Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This
can cause many headfakes and pull­out­your­hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.

• Disallows duplicate property names or parameter values. Strict mode throws an error when it detects a duplicate named property in
an object (e.g.,
var object = {foo: "bar", foo: "baz"};

) or a duplicate named argument for a function (e.g.,
function foo(val1, val2, val1){}

), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.

• Makes eval() safer. There are some differences in the way
eval()

behaves in strict mode and in non­strict mode. Most significantly, in strict mode, variables and functions declared inside of an
eval()

statement are not created in the containing scope (they are created in the containing scope in non­strict mode, which can also be a common
source of problems).

• Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non­
configurable properties of the object. Non­strict code will fail silently when an attempt is made to delete a non­configurable property, whereas
strict mode will throw an error in such a case.

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

• AvalHeight: Gives the height of client’s screen
• AvailWidth: Gives the width of client’s screen.
• ColorDepth: Gives the bit depth of images on the client’s screen
• Height: Gives the total height of the client’s screen, including the taskbar
• Width: Gives the total width of the client’s screen, including the taskbar

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 5/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

3. Code Output Questions
13. What will the code below output to the console and why?
1 (function(){
2   var a = b = 3;
3 })();
4  
5 console.log("a defined? " + (typeof a !== 'undefined'));
6 console.log("b defined? " + (typeof b !== 'undefined'));

Answer:
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most
JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.

However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:

var b = 3;

var a = b;

But in fact,
var a = b = 3;

is actually shorthand for:

b = 3;

var a = b;

As a result (if you are not using strict mode), the output of the code snippet would be:

1 a defined? false
2 b defined? true

14. What will the code below output to the console and why?
01 var myObject = {
02     foo: "bar",
03     func: function() {
04         var self = this;
05         console.log("outer func:  this.foo = " + this.foo);
06         console.log("outer func:  self.foo = " + self.foo);
07         (function() {
08             console.log("inner func:  this.foo = " + this.foo);
09             console.log("inner func:  self.foo = " + self.foo);
10         }());
11     }
12 };
13 myObject.func();

The above code will output the following to the console:

1 outer func:  this.foo = bar
2 outer func:  self.foo = bar
3 inner func:  this.foo = undefined
4 inner func:  self.foo = bar

In the outer function, both
this

and
self

refer to
myObject

and therefore both can properly reference and access
foo

In the inner function, though,
this

no longer refers to
myObject

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 6/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
. As a result,
this.foo

is undefined in the inner function, whereas the reference to the local variable
self

remains in scope and is accessible there. (Prior to ECMA 5, this in the inner function would refer to the global window object; whereas, as of
ECMA 5,
this

in the inner function would be
undefined

.)

15. What will the code below output? Explain your answer.
1 console.log(0.1 + 0.2);
2 console.log(0.1 + 0.2 == 0.3);

An educated answer to this question would simply be: “You can’t be sure. it might print out “0.3” and “true”, or it might not. Numbers in
JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.”

The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:

1 0.30000000000000004
2 false

16. Consider the following code snippet:
1 for (var i = 0; i < 5; i++) {
2   var btn = document.createElement('button');
3   btn.appendChild(document.createTextNode('Button ' + i));
4   btn.addEventListener('click', function(){ console.log(i); });
5   document.body.appendChild(btn);
6 }

(a) What gets logged to the console when the user clicks on “Button 4” and why?

(b) Provide one or more alternate implementations that will work as expected.

Answer:
(a) No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point that the
onclick

method is invoked (for any of the buttons), the
for

loop has already completed and the variable
i

already has a value of 5. (Bonus points for the interviewee if they know enough to talk about how execution contexts, variable objects,
activation objects, and the internal “scope” property contribute to the closure behavior.)

(b) The key to making this work is to capture the value of
i

at each pass through the
for

loop by passing it into a newly created function object. Here are three possible ways to accomplish this:

1 for (var i = 0; i < 5; i++) {
2   var btn = document.createElement('button');
3   btn.appendChild(document.createTextNode('Button ' + i));
4   btn.addEventListener('click', (function(i) {
5     return function() { console.log(i); };
6   })(i));
7   document.body.appendChild(btn);
8 }

17. What will the code below output to the console and why?
1 var arr1 = "john".split('');
2 var arr2 = arr1.reverse();
3 var arr3 = "jones".split('');
4 arr2.push(arr3);
5 console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(‐1));
6 console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(‐1));

Answer:
The logged output will be:

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 7/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

1 "array 1: length=5 last=j,o,n,e,s"
2 "array 2: length=5 last=j,o,n,e,s"
3 arr1 and arr2 are the same after the above code is executed for the following reasons:

• Calling an array object’s
reverse()

method doesn’t only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case,
arr1

).

• The
reverse()

method returns a reference to the array itself (i.e., in this case,
arr1

). As a result,
arr2

is simply a reference to (rather than a copy of)
arr1

. Therefore, when anything is done to
arr2

(i.e., when we invoke
arr2.push(arr3);

),
arr1

will be affected as well since
arr1

and
arr2

are simply references to the same object.

18. The following recursive code will cause a stack overflow if the array list is too large. How
can you fix this and still retain the recursive pattern?
01 var list = readHugeList();
02  
03 var nextListItem = function() {
04     var item = list.pop();
05  
06     if (item) {
07         // process the list item...
08         nextListItem();
09     }
10 };

Answer:
The potential stack overflow can be avoided by modifying the
nextListItem

function as follows:

01 var list = readHugeList();
02  
03 var nextListItem = function() {
04     var item = list.pop();
05  
06     if (item) {
07         // process the list item...
08         setTimeout( nextListItem, 0);
09     }
10 };

The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When
nextListItem

runs, if item is not null, the timeout function (
nextListItem

) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed­out event, the
next

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 8/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
item

is processed and a timer is set to again invoke
nextListItem

. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the
number of iterations.

19. What will the code below output to the console and why?
1 console.log(1 +  "2" + "2");
2 console.log(1 +  +"2" + "2");
3 console.log(1 +  ‐"1" + "2");
4 console.log(+"1" +  "1" + "2");
5 console.log( "A" ‐ "B" + "2");
6 console.log( "A" ‐ "B" + 2);

Answer:
The above code will output the following to the console:

1 "122"
2 "32"
3 "02"
4 "112"
5 "NaN2"
6 NaN

Why?

The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to
accommodate the operation being performed. Let’s see how this plays out with each of the above examples.

Example 1:
1 + "2" + "2"

Outputs:
"122"

Explanation: The first operation to be performed in
1 + "2"

. Since one of the operands (
"2"

) is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to
"1"

,
1 + "2"

yields
"12"

. Then,
"12" + "2"

yields
"122"

Example 2:
1 + +"2" + "2"

Outputs:
"32"

Explanation: Based on order of operations, the first operation to be performed is
+"2"

(the extra
+

before the first
"2"

is treated as a unary operator). Thus, JavaScript converts the type of

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 9/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
"2"

to numeric and then applies the unary
+

sign to it (i.e., treats it as a positive number). As a result, the next operation is now
1 + 2

which of course yields
3

. But then, we have an operation between a number and a string (i.e.,
3

and
"2"

), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding
"32"

Example 3:
1 + -"1" + "2"

Outputs:
"02"

Explanation: The explanation here is identical to the prior example, except the unary operator is
-

rather than
+

. So
"1"

becomes
1

, which then becomes
-1

when the
-

is applied, which is then added to
1

yielding
0

, which is then converted to a string and concatenated with the final
"2"

operand, yielding
"02"

Example 4:
+"1" + "1" + "2"

Outputs:
"112"

Explanation: Although the first
"1"

operand is typecast to a numeric value based on the unary
+

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 10/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second
"1"

operand, which is then concatenated with the final
"2"

operand, yielding the string
"112"

Example 5:
"A" - "B" + "2"

Outputs:
"NaN2"

Explanation: Since the – operator can not be applied to strings, and since neither
"A"

nor
"B"

can be converted to numeric values,
"A" - "B"

yields NaN which is then concatenated with the string
"2"

to yield “NaN2”.

Example 6:
"A" - "B" + 2

Outputs:
NaN

Explanation: As exlained in the previous example,
"A" - "B"

yields
NaN

. But any operator applied to NaN with any other numeric operand will still yield
NaN

20. What will be the output when the following code is executed? Explain.
1 console.log(false == '0')
2 console.log(false === '0')

Answer:
The code will output:

1 true
2 false

In JavaScript, there are two sets of equality operators. The triple­equal operator
===

behaves like any traditional equality operator would: evaluates to true if the two expressions on either of its sides have the same type and the
same value. The double­equal operator, however, tries to coerce the values before comparing them. It is therefore generally good practice to
use the
===

rather than
==

. The same holds true for
!==

vs

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 11/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
!=

4. Write Code Questions
21. What will the code below output to the console and why?
Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate
children). For each element visited, the function should pass that element to a provided callback function.

The arguments to the function should be:

• a DOM element
• a callback function (that takes a DOM element as its argument)

Answer
Visiting all elements in a tree (DOM) is a classic Depth­First­Search algorithm application. Here’s an example solution:

1 function Traverse(p_element,p_callback) {
2    p_callback(p_element);
3    var list = p_element.children;
4    for (var i = 0; i < list.length; i++) {
5        Traverse(list[i],p_callback);  // recursive call
6    }
7 }

22. Write a
sum

method which will work properly when invoked using either syntax below.
1 console.log(sum(2,3));   // Outputs 5
2 console.log(sum(2)(3));  // Outputs 5

There might be quite some ways to do this, but one of them is shown below:

1 function sum(x) {
2   if (arguments.length == 2) {
3     return arguments[0] + arguments[1];
4   } else {
5     return function(y) { return x + y; };
6   }
7 }

In JavaScript, functions provide access to an
arguments

object which provides access to the actual arguments passed to a function. This enables us to use the
length

property to determine at runtime the number of arguments passed to the function.

If two arguments are passed, we simply add them together and return.

23. Write a simple function (less than 80 characters) that returns a boolean indicating whether
or not a string is a palindrome.
The following one line function will return
true

if
str

is a palindrome; otherwise, it returns false.

1 function isPalindrome(str) {
2     str = str.replace(/\W/g, '').toLowerCase();
3     return (str == str.split('').reverse().join(''));
4 }

For example:

1 console.log(isPalindrome("level"));                   // logs 'true'
2 console.log(isPalindrome("levels"));                  // logs 'false'
3 console.log(isPalindrome("A car, a man, a maraca"));  // logs 'true'

4.1 Functional Javascript
24. Given the following array, build me an array of cars with those colours:
1 var colors = ['blue', 'black', 'red'];
var cars = ...;
https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 12/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
2 var cars = ...;

Answer:
1 var colors = ['blue', 'black', 'red'];
2 var cars = colors.map(buildCar);
3  
4 function buildCar (color) {
5     return new Car(color);
6 }

If they wrote a factory function wrapping Object.create in the first step, they can just map directly to that function, which makes this a bit more
elegant.

4.2 Dynamic Objects
25. I’ve created an array of 1000 cars. When I call run on the first car, I want it to run as normal.
When I call run on any of the others and any cars created in the future, I want it to run as
normal, but also log “The {color} car is now running”. to the console.

Answer:
1 cars[0].run = cars[0].run;
2  
3 var oldRun = Car.prototype.run;
4 Car.prototype.run = function () {
5     console.log("The " + this.color + " car is now running");
6     return oldRun.apply(this, arguments);
7 };

This covers:

• property lookup on objects
• the use of apply or call
• changing the behaviour of existing objects by modifying the prototype

4.3 Binding Shim
26. Can you shim the “bind” function?

Answer:
1 Function.prototype.bind = function (context) {
2     var self = this;
3     return function () {
4         return self.apply(context, arguments);
5     }
6 };

This can also be done by writing a bind function like underscore or CoffeeScript does, which is good if you don’t want to be modifying
JavaScript built­ins.

4.4 Animation
27. How could you implement moveLeft animation?

Answer:
Use
setInterval

that will place the element to the left position by some pixels in every 10ms. Hence, you will see the element moving towards the desired
position. When you call setInterval, it returns a timeId. After reaching the desired location, you have to clear the time interval so that function
will not be called again and again in every 10ms.

01 function moveLeft(elem, distance) {
02   var left = 0;
03  
04   function frame() {
05     left++;
06     elem.style.left = left + 'px';
07  
08     if (left == distance)
09       clearInterval(timeId)
10   }
11  
12   var timeId = setInterval(frame, 10); // draw every 10ms
13 }

4.5 Memorization
28. How could you implement cache to save calculation time for a recursive fibonacci function?

Answer:
You could use poor man’s memoization with a global variable. If fibonacci is already calculated it is served from the global memo array
otherwise it is calculated.

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 13/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

01 var memo = [];
02  
03 function _fibonacci(n) {
04    if(memo[n]){   
05     return memo[n];
06    }
07    else if (n < 2){
08      return 1;
09    }else{
10      fibonacci(n‐2) + fibonacci(n‐1);
11    }
12 }

29. How could you cache execution of any function?

Answer:
You could have a method where you will pass a function and it will internally maintain a cache object where calculated value will be cached.
When you will call the function with same argument, the cached value will be served.

01 function cacheFn(fn) {
02     var cache={};
03      
04     return function(arg){
05         if (cache[arg]){
06            return cache[arg];
07         }
08         else{
09            cache[arg] = fn(arg);
10             return cache[arg];
11         }
12     }
13 }

30. How could you set a prefix before everything you log? for example, if you log(‘my
message’) it will log: “(app) my message”?

Answer:
Just get the arguments, convert it to an array and unshift whatever prefix you want to set. Finally, use apply to pass all the arguments to
console.

1 function log(){
2   var args = Array.prototype.slice.call(arguments);
3   args.unshift('(app)');
4   console.log.apply(console, args);
5 }
6  
7 log('my message'); //(app) my message
8 log('my message', 'your message'); //(app) my message your message

5. Rapid Fire – Tricky Questions
31. Is ‘false’ false?
No. Because it’s a string with length greater than 0. Only empty strings can be considered as false.

32. Is ‘ ‘ false?
No. Because it’s not an empty string. There is a white space in it.

33. Is Boolean(function(){}) true or false?
true

. If you pass a truthy value to Boolean, it will be true.

34. What is 2 + true?
3. The plus operator between a number and a boolean or two boolean will convert boolean to number. Hence, true converts to 1 and you get
the result of 2+1.

35. What is ‘6’+9?
69. If one of the operands of the plus (+) operator is string it will convert the other number or boolean to string and perform a concatenation.
For the same reason, “2”+true will return “2true”.


36. What is the value of +’dude’?
NaN. The plus (+) operator in front of a string is an unary operator that will try to convert the string to number. Here, JavaScript will fail to
convert the “dude” to a number and will produce NaN.

37. If you have var y = 1, x = y = typeof x; What is the value of x?
“undefined”.

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 14/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

38. If var a = (2, 3, 5); what is the value of a?
5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

39. What is ­5%2?
­1. the result of remainder always gets the symbol of the first operand

40. What is typeof arguments?
Object. Arguments are like arrays but not arrays. They have length, can be accessed by index but you can’t push, pop and so on.

6. 10 Essential Questions
41. What is the drawback of creating true private methods in JavaScript?
One of the drawbacks of creating true private methods in JavaScript is that they are very memory­inefficient, as a new copy of the method
would be created for each instance.

01 var Employee = function (name, company, salary) {
02     this.name = name || "";       //Public attribute default value is null
03     this.company = company || ""; //Public attribute default value is null
04     this.salary = salary || 5000; //Public attribute default value is null
05  
06     // Private method
07     var increaseSalary = function () {
08         this.salary = this.salary + 1000;
09     };
10  
11     // Public method
12     this.dispalyIncreasedSalary = function() {
13         increaseSlary();
14         console.log(this.salary);
15     };
16 };
17  
18 // Create Employee class object
19 var emp1 = new Employee("John","Pluto",3000);
20 // Create Employee class object
21 var emp2 = new Employee("Merry","Pluto",2000);
22 // Create Employee class object
23 var emp3 = new Employee("Ren","Pluto",2500);

Here each instance variable
emp1

,
emp2

,
emp3

has its own copy of the increaseSalary private method. So, we don’t use private methods unless it’s necessary.

42. What will be the output of the code below?
1 var y = 1;
2  if (function f(){}) {
3    y += typeof f;
4  }
5  console.log(y);

The output would be
1undefined

. The
if

condition statement evaluates using
eval

, so
eval(function f(){})


returns
function f(){}

(which is true). Therefore, inside the if statement, executing
typeof

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 15/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
returns
undefined

because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.

43. What is a “closure” in JavaScript? Provide an example.
A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in
the parent function scope.

The closure has access to variables in three scopes:

• Variables declared in their own scope
• Variables declared in a parent function scope
• Variables declared in the global namespace

01 var globalVar = "abc";
02  
03 // Parent self invoking function
04 (function outerFunction (outerArg) { // begin of scope outerFunction
05     // Variable declared in outerFunction function scope
06     var outerFuncVar = 'x';   
07     // Closure self‐invoking function
08     (function innerFunction (innerArg) { // begin of scope innerFunction
09         // variable declared in innerFunction function scope
10         var innerFuncVar = "y";
11         console.log(         
12             "outerArg = " + outerArg + "\n" +
13             "outerFuncVar = " + outerFuncVar + "\n" +
14             "innerArg = " + innerArg + "\n" +
15             "innerFuncVar = " + innerFuncVar + "\n" +
16             "globalVar = " + globalVar);
17  
18     }// end of scope innerFunction)(5); // Pass 5 as parameter
19 }// end of scope outerFunction )(7); // Pass 7 as parameter

innerFunction

is closure that is defined inside
outerFunction

and has access to all variables declared and defined in the
outerFunction

scope. In addition, the function defined inside another function as a closure will have access to variables declared in the
global namespace

Thus, the output of the code above would be:

1 outerArg = 7
2 outerFuncVar = x
3 innerArg = 5
4 innerFuncVar = y
5 globalVar = abc

44. Write a mul function which will produce the following outputs when invoked:
javascript console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48

Below is the answer followed by an explanation to how it works:

1 function mul (x) {
2     return function (y) { // anonymous function
3         return function (z) { // anonymous function
4             return x * y * z;
5         };
6     };
7 }

Here the
mul

function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous
function that will take the third parameter and return the multiplication of the arguments that have been passed.

In JavaScript, a function defined inside another one has access to the outer function’s variables. Therefore, a function is a first­class object that 
can be returned by other functions as well and be passed as an argument in another function.

• A function is an instance of the Object type
• A function can have properties and has a link back to its constructor method
• A function can be stored as a variable
• A function can be passed as a parameter to another function
• A function can be returned from another function

45. How to empty an array in JavaScript?
https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 16/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
45. How to empty an array in JavaScript?
For instance,

1 var arrayList =  ['a','b','c','d','e','f'];

One Solution
A solution would obviously be setting the array length to zero.

1 arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables
that point to the original array.

46. What will be the output of the following code?
1 var output = (function(x){
2     delete x;
3     return x;
4   })(0);
5  
6   console.log(output);

The output would be
0

. The
delete

operator is used to delete properties from an object. Here
x

is not an object but a local variable.
delete

operators don’t affect local variables.

47. What is the difference between the function declarations below?
1 var foo = function(){
2    // Some code
3 };

1 function bar(){
2     // Some code
3  };

The main difference is the function foo is defined at
run-time

whereas function
bar

is defined at parse time.

48. What will be the output of the code below?
1 var Employee = {
2   company: 'xyz'
3 }
4 var emp1 = Object.create(Employee);
5 delete emp1.company
6 console.log(emp1.company);

The output would be
xyz

. Here,
emp1

object has
company


as its prototype property. The
delete

operator doesn’t delete prototype property.

emp1

object doesn’t have company as its own property. You can test it

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 17/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
console.log(emp1.hasOwnProperty('company')); //output : false

. However, we can delete the
company

property directly from
theEmployee

object using
delete Employee.company

. Or, we can also delete the
emp1

object using the
__proto__

property
delete emp1.__proto__.company

49. Consider the following code:
1 (function() {
2    var a = b = 5;
3 })();
4  
5 console.log(b);

What will be printed on the console?

The code above prints
5

The trick of this question is that in the IIFE there are two assignments but the variable
a

is declared using the keyword
var

. What this means is that
a

is a local variable of the function. On the contrary,
b

is assigned to the global scope.

The other trick of this question is that it doesn’t use strict mode (
'use strict';

) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that
strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:

1 (function() {
2    'use strict';
3    var a = window.b = 5;
4 })();
5  
6 console.log(b);

6.1 Hoisting
50. What’s the result of executing this code and why?
01 function test() {
02    console.log(a);
03    console.log(foo()); 
04     
05    var a = 1;
06    function foo() {
07       return 2;
08    }
09 }
10  
11 test();

The result of this code is

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 18/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
undefined

and
2

The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So,
at the time the variable
a

is printed, it exists in the function (it’s declared) but it’s still
undefined

. Stated in other words, the code above is equivalent to the following:

01 function test() {
02    var a;
03    function foo() {
04       return 2;
05    }
06  
07    console.log(a);
08    console.log(foo());
09     
10    a = 1;
11 }
12  
13 test();

7. General Questions
51. What is ‘this’ keyword in JavaScript?
this

keyword is used to point at the current object in the code. For instance: If the code is presently at an object created by the help of the ‘new’
keyword, then ‘this’ keyword will point to the object being created.

52. What is the difference between ViewState and SessionState?
‘ViewState’ is specific to a page in a session.
‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.

53. Does JavaScript support automatic type conversion?
Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers.

54. How can you read and write a file using JavaScript?
There are two ways to read and write a file using JavaScript

• Using JavaScript extensions
• Using a web page and Active X objects

55. How can you read and write a file using JavaScript?
The
parseInt()

function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second
parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be –

1 parseInt ("4F", 16);

56. What is the use of Void(0)?
Void(0)

is used to prevent the page from refreshing and parameter “zero” is passed while calling. 
Void(0)

is used to call another method without refreshing the page.

57. What are JavaScript Cookies?

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 19/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible
after its declaration.

Anonymous function declaration:

1 var wcg = function() {
2   
3 alert('I am anonymous');
4   
5 };
6   
7 wcg();

58. How can a particular frame be targeted, from a hyperlink, in JavaScript?
This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute.

1 <a href='newpage.htm' target='newframe'>New Page</a>

59. Explain the role of deferred scripts in JavaScript?
By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is
slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script
till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.

60. How can a particular frame be targeted, from a hyperlink, in JavaScript?
innerHTML

content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge
code in the document and, thus, make the web page unstable.

61. What does a timer do and how would you implement one?
• Setting timers allows you to execute your code at predefined times or intervals.
• This can be achieved through two main methods:
setInterval();

and
setTimeout();


setInterval()

accepts a function and a specified number of milliseconds.
ex)
setInterval(function(){alert(“Hello, World!”),10000)

will alert the “Hello, World!” function every 10 seconds.

setTimeout()

also accepts a function, followed by milliseconds.
setTimeout()

will only execute the function once after the specified amount of time, and will not reoccur in intervals.

62. Explain the concept of unobtrusive Javascript?
Unobtrusive JavaScript is basically a JavaScript methodology that seeks to overcome browser inconsistencies by separating page functionality
from structure. The basic premise of unobtrusive JavaScript is that page functionality should be maintained even when JavaScript is unavailable
on a user’s browser.

63. What is “event delegation” and how does it work?
Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element. When an event
is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This
process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree. The target element of any
event is the originating element, the button in our example, and is stored in a property of the event object. Using event delegation it’s possible
to add an event handler to an element, wait for an event to bubble up from a child element and easily determine from which element the event 
originated.

64. What is the importance of tag?
– JavaScript is used inside <SCRIPT> tag in HTML document. The tags that are provided the necessary information like alert to the browser for
the program to begin interpreting all the text between the tags.
– The <script> tag uses JavaScript interpreter to handle the libraries that are written or the code of the program.

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 20/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016
– JavaScript is a case sensitive language and the tags are used to tell the browser that if it is JavaScript enabled to use the text written in
between the <Script> and >/Script< tags.

65. What is the difference between window.onload and onDocumentReady?
The
window.onload

event won’t trigger until every single element on the page has been fully loaded, including images and CSS. The downside to this is it might
take a while before any code is actually executed. You can use
onDocumentReady

to execute code as soon as the DOM is loaded instead.

8. A Final Note
I hope this list serves you as a refresher for what you already know about Javascript. Aside from being able to discuss the topics listed above,
you should also be prepared to create whiteboard examples for each one. If you’re a pro and use JavaScript everyday, you’ll breeze through
these.

However, what remains of a great importance is having the concentration to listen carefully and use your knowledge/experience alongside with
logic to answer any question. The idea of the interview sometimes is not the actual programming language, but to identify if the candidate is
able to solve real life problems on the spot.

Still with us? Wow, that was a huge article about different types of questions that can be used in a JavaScript interview. If you enjoyed this,
then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers!

So, what other JavaScript interview questions are there? Let us know in the comments and we will include them in the article! Happy coding!

Tagged with:  INTERVIEW

Do you want to know how to develop your skillset to become a Web
Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
 
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
 
and many more ....
 
Email address:
Your email address

 
Sign up

3 COMMENTS 

Manu Gupta
January 8th, 2016 at 7:37 pm

How can I download these questions. I do not see any link.
Please help.
Reply

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 21/22
8/5/2016 65 JavaScript Interview Questions and Answers – The ULTIMATE List (PDF Download) | Web Code Geeks ­ 2016

Eleftheria Drosopoulou
January 9th, 2016 at 1:13 pm

Hello Manu,
First, you need to join our newsletter here: http://eepurl.com/6iVnH
After you enter a VALID email address, you will need to verify your subscription.
A verification email will be sent to you and after you successfully verify your email,
you will get a final welcome email which will contain the links to download the ebooks!
Reply

Charlie
July 8th, 2016 at 7:23 am

I noticed that #57 is titled to talk about cookies and instead talks about anonymous functions…
Reply

LEAVE A REPLY

Your email address will not be published. Required fields are marked *

Name *

Email *

Website

Sign me up for the newsletter!

 Receive Email Notifications?
no, do not subscribe instantly
Or, you can subscribe without commenting.

Post Comment

KNOWLEDGE BASE HALL OF FAME ABOUT WEB CODE GEEKS

WCGs (Web Code Geeks) is an independent online community focused on creating
Courses HTML5 Drag and Drop Example
ultimate Web developers resource center; targeted at the technical architect, tech
team lead (senior developer), project manager and junior developers alike. WCGs
Resources Javascript copy to clipboard example
the Web designer, Web developer and Agile communities with daily news written 
domain experts, articles, tutorials, reviews, announcements, code snippets and op
Tutorials JavaScript Document Ready Example
source projects.
Whitepapers JavaScript For Loop Example
DISCLAIMER
JavaScript Sort Array Example
THE CODE GEEKS NETWORK
JavaScript String Compare example All trademarks and registered trademarks appearing on Web Code Geeks are the
property of their respective owners.
.NET Code Geeks JavaScript Submit Form Example

Java Code Geeks JQuery Autocomplete Widget Example

System Code Geeks Single Page Apps

Web Code Geeks Twitter Bootstrap Modal Example

Web Code Geeks and all content copyright © 2010­2016, Exelixis Media P.C. | Terms of Use | Privacy Policy | Contact  

https://www.webcodegeeks.com/javascript/javascript­interview­questions­answers/ 22/22

You might also like