Javascript Interview Questions.pdf
Javascript Interview Questions.pdf
INTERVIEW
QUESTIONS
AND
ANSWERS
COMPLETE JAVASCRIPT INTERVIEWS BOOKLET
HIMANSHU KUMAR
@the_rising_engineers
Theoretical Questions
1. Can you name two programming paradigms important for JavaScript app de-
velopers?
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: - Function purity - Avoiding side-effects - Simple function composition
OOP (Object-Oriented
3 Whatisthedifferencebetweenclassicalinheritanceandprototypalinheritance?
Class Inheritance: instances inherit from classes (like a blueprint - a description of the class), and create sub-class relation-
ships: 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.
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,
causes and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which
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.
In JavaScript, there are three primary data types, two composite data types, and two special data types.
Primary Data Types
• String
• Number
• Boolean
• Object
• Array
• Null
• Undefined
7. Whatisthedifferencebetween"=="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.
• 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.
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 the beginning
of a JavaScript source file?
Screen objects are used to read the information from the client’s screen. The properties of screen objects are
13. What will the code below out put to the console and why?
(function(){
vara=b=3;
})();
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;
Butinfact,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:
a defined? false
b defined? true
14. What will the code below out put to the console and why?
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo); console.log("inner
func: self.foo = " + self.foo);
}());
}
};
myObject.func();
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. 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.
console.log(0.1 + 0.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:
0.30000000000000
004 false
(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:
17. What will the code below out put to the console and why?
Answer:
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?
if (item) {
// process the list item...
nextListItem();
}
};
Answer:
The potential stack overflow can be avoided by modifying the nextListItem function as follows:
if (item) {
// process the list item...
setTimeout( nextListItem, 0);
}
};
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 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 out put to the console and why?
Answer:
Why?
The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conver-
sion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.
Example1: 1 + "2" + "2"Outputs: "122"Explanation: Thefirstoperationtobeperformedin1 + "2". Sinceoneof
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".
Example2:1 + +"2" + "2"Outputs:"32"Explanation:Basedonorderofoperations,thefirstoperationtobeperformed
is +"2" (the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "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 + 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.
console.log(false == ’0’)
console.log(false === ’0’)
Answer:
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 !=.
21. What will the code below out put 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:
function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
22. Write a below sum method which will work properly when invoked using
either syntax
console.log(sum(2,3));
console.log(sum(2)(3));
There might be quite some ways to do this, but one of them is shown below:
}
function sum(x) {
if (arguments.length == 2) {
return arguments[0] + arguments[1];
} else {
return function(y) { return x + y; };
}
}
// Outputs 5
In JavaScript, functions provide access to an 5
// Outputs 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.
The following one line function will return true if str is a palindrome; otherwise, it returns false.
function isPalindrome(str) {
str = str.replace(/\W/g, ’’).toLowerCase();
return (str == str.split(’’).reverse().join(’’));
}
For example:
console.log(isPalindrome("level")); // logs ’true’
console.log(isPalindrome("levels")); // logs ’false’
console.log(isPalindrome("A car, a man, a maraca")); // logs ’true’
Given the following array, build me an array of cars with those colours:
Answer:
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.
DynamicObjects
25. I’ve created an array of 1000 cars. When I call run on the first car,Iwantittorunasnormal. 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:
cars[0].run = cars[0].run;
This covers:
property lookup on objects the use of apply or call changing the behaviour of existing objects by modifying the prototype
Binding Shim
Answer:
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.
Animation
27. HowcouldyouimplementmoveLeftanimation?
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.
function moveLeft(elem, distance) {
var left = 0;
function frame() {
left++;
elem.style.left = left + ’px’;
if (left == distance)
clearInterval(timeId)
}
Memorization
28. How could you implement cache to save calculation time for are cursive 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.
var memo = [];
function _fibonacci(n) {
if(memo[n]){
return memo[n];
}
else if (n < 2){
return 1;
}else{
fibonacci(n-2) + fibonacci(n-1);
}
}
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.
function cacheFn(fn) {
var cache={};
return function(arg){
if (cache[arg]){
return cache[arg];
}
else{
cache[arg] = fn(arg);
return cache[arg];
}
}
}
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.
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift(’(app)’);
console.log.apply(console, args);
}
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.
34. Whatis2+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.
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".
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.
"undefined".
5 - The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
-1. the result of remainder always gets the symbol of the first operand
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.
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.
var Employee = function (name, company, salary) {
this.name = name || ""; //Public attribute default value is null
this.company = company || ""; //Public attribute default value is null
this.salary = salary || 5000; //Public attribute default value is null
// Private method
var increaseSalary = function () {
this.salary = this.salary + 1000;
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSlary();
console.log(this.salary);
};
};
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);
emp1, emp2, emp3
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 f returns undefined because the if statement code executes
at run time, and the statement inside the if condition is evaluated during run time.
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
var globalVar = "abc";
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:
outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc
44. Write a mul function which will produce the following outputs when invoked:
};
};
}
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
from can be stored as a variable A function can be passed as a parameter to another function A function can be returned
another function
For instance,
var arrayList = [’a’,’b’,’c’,’d’,’e’,’f’];
OneSolution
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.
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.
function bar(){
// Some code
};
The main difference is the function foo is defined at run-time whereas function bar is defined at parse time.
var Employee = {
company: ’xyz’
}
var emp1 = Object.create(Employee);
delete emp1.company
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 console.log(emp1.hasOwnProperty(’com pany’));//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.
(function() {
vara=b=5;
})();
console.log(b);
console.log(b);
Hoisting
function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();
function test() {
var a;
function foo() {
return 2;
}
console.log(a);
console.log(foo());
a=1;
}
test();
General Questions
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 View State and Session State?
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.
Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers.
54. How can your read and write a file using JavaScript?
There are two ways to read and write a file using JavaScript
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 -
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.
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:
var wcg = function() {
alert(’I am anonymous’);
};
wcg();
This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute.
<a href="newpage.htm" target="newframe">New Page</a>
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.
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.
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.
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. Whatistheimportanceoftag?
• 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.
• 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 onDocument Ready?
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.