Sitemap

JavaScript Interview Question & Answer

13 min readMay 12, 2020

--

Press enter or click to view image in full size
Job Interview Preparation

Today I am going to discuss the most common JavaScript interview questions and answers. I hope today you will learn the most important questions and answer. Let’s start.

1. window vs document

Question: Is there any difference between window and document?

Answer: Yes. JavaScript has a global object and everything runs under it. the window is that global object that holds global variables, global functions, location, history everything is under it. Besides, setTimeout, ajax call (XMLHttpRequest), console or localStorage are part of window.

2. window.onload vs document.onload

Question: Does document.onload and window.onload fire at the same time?

Answer: window.onload is fired when DOM is ready and all the contents including images, css, scripts, sub-frames, etc. finished loaded. This means everything is loaded.

document.onload is fired when DOM (DOM tree built from markup code within the document)is ready which can be prior to images and other external content is loaded.

Think about the differences between window and document, this would be easier for you.

3. attribute vs property

Question: Is attribute similar to the property?

Answer: attributes are just like an attribute in your HTML tag (XML style attribute) inside the starting tag. HTML attributes are exposed to the DOM via property. Hence, a property is created when DOM is parsed for each attribute in the HTML tag. If you change an attribute only the value of the property will change. However, the value of the attribute will remain the same.

4. DOM Query

Question: What are the different ways to get an element from DOM?

Answer: You can use the following methods in document

  • getElementById to get an element that has the provided Id.
  • getElementsByClassName to get a novelist (nodelist is not an array, rather it is array-like object) by providing a class name.
  • getElementsByTagName to get a nodelist by the provided tag name.
  • querySelector you will pass css style selector (jquery style) and this will retrurn first matched element in the DOM.
  • querySelectorAll will return a non-live nodelist by using depth-first pre order traversal of all the matched elements. Non-live means, any changes after selecting the elements will not be reflected.

There are two more options but I dont use them frequently-

  • getElementsByName returns the list of elements by the provided name of the html tag
  • getElementsByTagNameNS returns elements with particular tag name within the provided namespace

5. Fastest way to Query DOM

Question: What is the fastest way to select elements by using css selectors?

Answer: It depends on what you are selecting. If you have an ID of an element getElmentById is the fastest way to select an element. However, you should not have so many ID in you document to avoid style repetition. css class getElementsByClassName is the second quickest way to select an element

Here is the list. As we go downwards through the list, it takes more time to select elements.

  • ID (#myID)
  • Class (.myClass)
  • Tag (div, p)
  • Sibling (div+p, div~p)
  • child (div>p)
  • Descendant (div p)
  • Universal (*)
  • Attribute (input[type=”checkbox”])
  • Pseudo (p:first-child)

6. Use forEach on NodeList

Question: How come, I can’t use forEach or similar array methods on a NodeList?

Answer: Yeah. Both array and nodeList have length and you can loop through elements but they are not same object.

Both are inherited from Object. However array has different prototype object than nodeList. forEach, map, etc are on array.prototype which doesn’t exist in the NodeList.prototype object. Hence, you don’t have forEach on a nodeList

7. getElementsByAttribute

Question: If you need to implement getElementByAttribute, how would you implement it?

Answer: First, get all the elements in the DOM. You can either get it by Tag Name ‘*’ and then check whether they have the particular attribute. In this case, even if attribute is null that will be captured. If you need to check the value, you should be able to do it by passing one extra parameter and comparing it in the if block.

8. add class

Question: How would you add a class to an element by query selector?

Answer: Very simple. Just get the element and add the classname to the classlist.

9. Check Descendant

Question: How could I verify whether one element is child of another?

Answer: First check whether the passed parent is the direct parent of the child. If not, keep moving upward to the root of the tree.

10. innerHTML vs appendChild

Question: What is the best way to create a DOM element? Set inner HTML or use createElement?

Answer: When you set innerHTML property, the browser removes all the current children of the elements. Parse the string and assign the parsed string to the element as children.

For example, if you want to add a list item to an unordered list. You can get the element and set the innerHTML of the element like

11. CrateDocumentFragment

Question: What is createDocumentFragment and why you might use it?

Answer: documentFragment a very lightweight or minimal part of a DOM or a subtree of a DOM tree. It is very helpful when you are manipulating a part of DOM for multiple times. It becomes expensive to hit a certain portion of DOM for hundreds time. You might cause reflow for hundred times. Stay tuned for reflow.

12. reflow

Question: What is reflow? What causes reflow? How could you reduce reflow?

Answer: Aha… so many questions at the same time. Take a breathe Mr. Interviewer.

reflow: When you change size or position of an element in the page, all the elements after it has to change their position according to the changes you made. For example, if you change height on an element, all the elements under it has to move down in the page to accomodate a change in height. Hence, flow of the elements in the page is changed and this is called reflow.

13. repaint

Question: What is repaint and when does this happen?

Answer: repaint happens when you change the look of an element without changing the size and shape. This doesn’t cause reflow as geometry of the element didn’t changed.

How it happens:

  • change background color
  • change text color
  • visibility hidden

14. DOM ready

Question: How could you make sure to run some javaScript when DOM is ready like $(document).ready?

Answer: There are four different ways-

option-1: Put your script in the last tag of html body element. DOM would be ready by the time browser hits the script tag.

option-2: Place your code inside a DOMContentLoaded handler. This event will be fired when DOM is completely loaded.

option-3: Watch changes in the readyState of the document. And the last state is “complete” state, you can put your code there.

option-4: Search jquery source code and copy dom ready function. In that case, you have a ready function that works in the older browsers as well without loading the whole jquery library.

15. Event bubble

Question: What is the event bubble? How does the event flow?

Answer: To understand the event bubble, you have to understand what happens when you click on anything on a page.

Where you clicked: If you have a table with multiple rows and multiple columns and you click in one of the cells

  • You will think that you have clicked on the cell and the browser will know that you have a click handler with the cell that will be fired immediately.
  • You are completely wrong. Right away, the browser doesn’t know where you have clicked.

16. Event Delegate

Question: How would you destroy multiple list items with one click handler?

Easy Solution: If you have one hundred list items that have similar events to handle. You can write one hundred event handler (actually copy-paste) same code in 99 places. This works but if something changes in the event handler, you have to change in one hundred places. This doesn’t call job security. This is called screwed up.

17. destroy button

Question: Create a button that is destroyed by clicking on it but two new buttons are created in its place.

Answer: One way of solving is to attach an event handler with the button to destroy itself and append two. However, we can leverage the event delegate. If we attach the event handler to the parent div instead of the button itself. We don’t have to add the event handler to each button we create. So, we will take advantage of event bubbling.

18. Capture all click

Question: How could you capture all clicks on a page?

Get Shakil Ahmed’s stories in your inbox

Join Medium for free to get updates from this writer.

Answer: You can leverage, event bubble to capture all the clicks. As all the clicks will be bubbled up to the body.

19. All text in a page

Question: How can you get all the texts in a web page?

Answer: The easiest way to get all the text is to get the innerText of body tag.

20. null vs undefined

Question: What are the differences between null and undefined?

Answer: JavaScript has two distinct values for nothing, null and undefined.

undefined

undefined means, the value of the variable is not defined. JavaScript has a global variable undefined whose value is "undefined" and typeof undefined is also "undefined". Remember, undefined is not a constant or a keyword. undefined is a type with exactly one value: undefined. Assigning a new value to it does not change the value of the type undefined.

8 Ways to get Undefined:

  • A declared variable without assigning any value to it.
  • Implicit returns of functions due to missing return statements.
  • return statements that do not explicitly return anything.
  • Lookups of non-existent properties in an object.
  • Function parameters that have not passed.
  • Anything that has been set to the value of undefined.
  • Any expression in the form of the void(expression)
  • The value of the global variable undefined

null

null means the empty or non-existent value which is used by programmers to indicate “no value”. null is a primitive value and you can assign null to any variable. null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because of typeof null returns "object".

Btw, null == undefined

21. == Vs ===

Question: What are the differences between == and ===?

Answer: The simplest way of saying that, == will not check types and === will check whether both sides are of the same type. So, == is tolerant. But under the hood, it converts to its convenient type to have both in the same type and then do the comparison.

=== compares the types and values. Hence, if both sides are not the same type, the answer is always false. For example, if you are comparing two strings, they must have identical character sets. For other primitives (number, boolean) must share the same value.

The rule for implicit coercion: Comparison by using == does implicit type conversion under the hood. And rules for implicit coercion are as follows-

  • If both operands are same type use ===
  • undefined == null
  • If one operand is string another is number, convert string to number
  • If one is boolean and another is non-boolean, convert boolean to the number and then perform a comparison
  • While comparing a string or number to an object, try to convert the object to a primitive type and then try to compare

Be careful while comparing objects, identifiers must reference the same objects or the same array.

22. Truthy isn’t Equal to true

Question: As [] is true, []==true should also be true. right?

Answer: You are right about the first part, []an empty array is an object and an object is always truthy. Hence, if you use if([]){console.log('its true')} you will see the log.

However, a special case about == (double equal) is that it will do some implicit coercion.

Since the left and right sides of the equality are two different types, JavaScript can’t compare them directly. Hence, under the hood, JavaScript will convert them to compare. the first right side of the equation will be coerced to a number and number of true would be 1.

After that, JavaScript implementation will try to convert [] by usingtoPrimitive (JavaScript implementation). since [].valueOf is not primitive will use toString and will get ""

Now you are comparing “== 1 and still left and right is not the same type. Hence left side will be converted again to a number and an empty string will be 0.

Finally, they are of the same type, you are comparing 0 === 1 which will be false.

23. log-prefix

Question: 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 the console.

24. Scope and hoisting

Question: What will you see in the console for the following example?

var a = 1; function b() { a = 10; return; function a() {} } b(); console.log(a);

25. Closures Inside Loops

Question: Look at the code below, you have a for loop if you have setTimeout inside it. If log the loop counter inside setTimeout, what will be logged?

for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 10);
}

Answer: The above will not output the numbers 0 through 9, but will simply print the number 10 ten times.

Explanation: The console log is inside the anonymous function of setTimeout and setTimeout is executed when current call stack is over. So, the loop finishes and before setTimeout get the chance to execute. However, anonymous functions keep a reference to i by creating a closure. Since, the loop is already finished, the value i has been set to 10. When setTimeout use the value of i by reference, it gets the value of i as 10. Hence, you see 10 ten times.

Solution: You can fix it by avoiding closure. Just create a IIFE (Immediately Invoked Function Expression), it will create its own scope and you can pass i to the function. In that case i will be a local variable (will not refer to i in the closure) and value of the i in every loop will be preserved.

for(var i = 0; i < 10; i++) {
setTimeout((function(i) {
console.log(i);
})(i), 10)
}

Alternative Solution: Look at the code below and use your brain (if any).

for(var i = 0; i < 10; i++) {
setTimeout(console.log.bind(console, i), 10);
}

26. delete can delete but

Question: Look at the code below, I have a property in a object and I am creating a new object where I am setting it to a new value. If I delete that property what will i get if I try to access that property?

var myObject = {
price: 20.99,
get_price : function() {
return this.price;
}
};
var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price());

Answer: You will see 20.99

Explanation: This is very interesting question. When you create object.create(myObject) you are creating new object where the myObject will be the parent of the newly created object. Hence the price property will be at the parent.

When you are assigning some value to customObject.price, you are creating a new property on the child. This means, when you delete customObject.price it deletes the price property in the customObject (in the child). However, when you call the method getprice, first it looks for this.price in the child since the customObject doesn't have price property, JavaScript executor walks through the prototype chain towards the parent. Since customObject was inherited from myObject and myObject has a price property, the get_price method returns the price from parent. Hence, you are getting 20.99

27. Pass by value or by reference

Question: Does JavaScript pass parameter by value or by reference?

Answer: Primitive type (string, number, etc.) are passed by value and objects are passed by reference. If you change a property of the passed object, the change will be affected. However, you assign a new object to the passed object, the changes will not be reflected.

var num = 10,
name = "Addy Osmani",
obj1 = {
value: "first value"
},
obj2 = {
value: "second value"
},
obj3 = obj2;

function change(num, name, obj1, obj2) {
num = num * 10;
name = "Paul Irish";
obj1 = obj2;
obj2.value = "new value";
}

change(num, name, obj1, obj2);

console.log(num); // 10
console.log(name);// "Addy Osmani"
console.log(obj1.value);//"first value"
console.log(obj2.valuee);//"new value"
console.log(obj3.valuee);//"new value"

ref: Snook: passing by value or reference

28. memoization

Question: 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.

var memo = [];function _fibonacci(n) {
if(memo[n]){
return memo[n];
}
else if (n < 2){
return 1;
}else{
fibonacci(n-2) + fibonacci(n-1);
}
}

Better Implementation: implement memoization in JavaScript

29. Cache function execution

Question: 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.

function cacheFn(fn) {
var cache={};

return function(arg){
if (cache[arg]){
return cache[arg];
}
else{
cache[arg] = fn(arg);
return cache[arg];
}
}
}

Question: What if you are passing more than one argument?

Answer: First we have to use arguments to get all the parameters passed to the function and then we can generate key for the cache object. Generating key for the cache object could be tricky and one solution could be just get the all the parameters and concatenate those. Look at the code below.

return function(){
var args = arguments;
var key = [].slice.call(args).join('');
if(cache[key]){
return cache[key];
}
else{
cache[key] = fn.apply(thi, args);
return cache[key];
}
}

30. JQuery style chaining

Question: If you need to implement the following chaining with call back, how will you implement it?

function slow(callback) {
setTimeout(function(){
if (Math.random() > 0.5) {
return callback("Error 417",null)
}
callback(null, {id:123})
},500);
}
function exec(fn){
//write your code here
}
exec(slow).done(function(data){
console.log(data);
}).fail(function(err){
console.log("Error: " + err);
})

Too much sleepy now. will try to put it up tomorrow.

var obj = {   // every method returns obj---------v
first: function() { console.log('first'); return obj; },
second: function() { console.log('second'); return obj; },
third: function() { console.log('third'); return obj; }
}
obj.first().second().third();

ref: jquery like chaining or jquery like chaining

No more today. If you want to know more please search google and keep learning. If I make any mistakes please inform me. I will try my best to solve it. Thank you all.

--

--

Shakil Ahmed
Shakil Ahmed

Hi, I am Shakil Ahmed. I am a student of Computer Science and Engineering at Green University. I am a web developer and programming lover.