JavaScript Interview Questions

Serajur Reza Chowdhury
8 min readMay 12, 2020

--

DOM and Events

1. What is window and document in JavaScript?

Window represents the browser’s window. All global JavaScript objects, functions, variables are part of window object.

Document represents the web page. Document represents document object model(DOM) and DOM is the object oriented representation of the HTML you have written.

2. How to find HTML elements in DOM?

There are 3 ways to do it.

Find an element by element id — document.getElementById(id)

Find elements by tag name — document.getElementsByTagName(name)

Find elements by class name — document.getElementsByClassName(name)

3. What is the difference between innerHTML and outerHTML?

InnerHTML is a property of a DOM element that represents the content inside the element. It can be normal text or html markup or both.

OuterHTML is a property of a DOM element that returns the content inside the element with the tag representation.

e.g. — <p id=’info’>The name is Bond, James Bond.</p>

The innerHTML of info is — The name is Bond, James Bond.

The outerHTML of info is — <p id=’info’>The name is Bond, James Bond.</p>

4. What is the difference between innerHTML and innerText?

InnerHTML is a property of a DOM element that represents the content inside the element. It can be normal text or html markup or both.

But innerText returns only the normal texts inside an element.

e.g. — <p id=’info’>The name is Bond, <span>James Bond.</span></p>

The innerHTML of info is — The name is Bond, <span>James Bond.</span>

The innerText of info is — The name is Bond, James Bond.

5. How to add and delete elements in DOM?

Creating a DOM element — document.createElement(element)

Removing a DOM element — document.removeChild(element)

Appending a DOM element — document.appendChild(element)

Replacing a DOM element — document.replaceChild(new, old)

Write into HTML output stream — document.write(text)

6. What is event bubble?

Event bubble is something which searches from the window to the end of tree to find where an event is occurred.

7. How do the browser identify the item an event occurred to?

Capture — The browser identifies your event after your event. Then it starts from window, then document, then one after another it traverses the DOM tree to find the element.

Target — As the traversal goes lower, the browser looks for the eventhandler of element the event occurred.

Bubble — After firing the event of the element, the browser traverses back to the root. During going up, the browser checks whether there is event handler for the parent components. If so, the browser fires them.

8. What is event delegate?

Event delegate is assigning events dynamically to the elements. Here, we can target an HTML element with several children and assign event handlers dynamically to them.

9. What is event propagation?

Event propagation stops firing event handlers to the parent elements. We can stop all the parent event propagation using event.stopPropagation() and the immediate parent using event.stopImmediatePropagation.

10. What does preventDefault does?

The preventDefault() method cancels an event if it is cancelable, which means it stops the default event from occurring.

It is widely used in form submission, where it submits the form but does not refresh the page.

11. How to get parent and child nodes from DOM?

Getting parentNode — var c= document.getElementById(‘li’).parentNode

Getting childNode — var c= document.getElementById.childNodes

Syntax

1. What is the difference between null and undefined?

Undefined means the value of a variable is not defined. JavaScript has a global variable undefined whose value is “undefined” and typeof undefined is also “undefined”. undefined is a type with exactly one value: undefined.

Null means empty or non-existing value which is used by programmer to indicate “no value”. null is a primitive value and you can assign null to any variable.

· 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 void(expression)

· The value of the global variable undefined

2. Difference between (==) and (===)?

(==) checks only the data and (===) checks both type and data.

(==) tries to match two expressions by their values. If both expression types not matched, it forcefully tries make convert the left expressions type. If not then it returns false.

(===) tries to match both type and data. If any dissimilarities it returns false.

3. What are the falsy, truthy values in JavaScript?

Falsy — 0, null, undefined, false,’’,NaN.

Truthy — true and everything that are not false.

4. How many ways you can declare variables?

3 ways. var, let, const.

5. How many for loops are there in JavaScript?

for, for .. of, for .. in.

6. What is this in JavaScript?

this is always refer to an object and depends on how function is called. There are 7 different cases where the value of this varies.

· In the global context or inside a function this refers to the window object.

· Inside IIFE (immediate invoking function) if you use “use strict”, value of this is undefined. To pass access window inside IIFE with “use strict”, you have to pass this.

· While executing a function in the context of an object, the object becomes the value of this

· Inside a setTimeout function, the value of this is the window object.

· If you use a constructor (by using new keyword) to create an object, the value of this will refer to the newly created object.

· You can set the value of this to any arbitrary object by passing the object as the first parameter of bind, call or apply

· For dom event handler, value of this would be the element that fired the event

7. How String with an integer can be added?

From left to right. Before string everything is added normally. From the string everything will start to be concatenated.

e.g. 1+5+”2”+8=628

Here, 1 and 5 are added normally. After they are added, everything will concatenated. So, the result is 628.

8. What does Math.max and Math.min return in empty parameters?

Math.max(): -Infinity

Math.min(): Infinity

9. Why is isNaN returns true for strings?

Because isNaN checks any number type data that is NaN. For other types, it returns true.

10. How parameters are sent to function/ How function can access its parameters?

They can be accessed using arguments. It can be accessed as an array. But it is an array like Object.

11. Why ternary operators are used?

Ternary operators are used as inline conditional startements

var age= 20;

var a= (age >=18)? “Men”: “Kid”

12. What does “use strict” do?

“use strict” is a feature that makes our code in strict mode. It helps to avoid bugs early in our code and adds restrictions to it.

Functions

1. What are apply, bind and call?

Apply — Calls a function with a given ‘this’ value and arguments provided as an array.

const person = {

name: “Marko Polo”

};

function greeting(greetingMessage) {

return `${greetingMessage} ${this.name}`;

}

greeting.apply(person, [‘Hello’]); // returns “Hello Marko Polo!”

Call — Calls a function with a given ‘this’ value and arguments provided individually.

const person = {

name: “Marko Polo”

};

function greeting(greetingMessage) {

return `${greetingMessage} ${this.name}`;

}

greeting.call(person, ‘Hello’); // returns “Hello Marko Polo!”

The difference between the two is apply takes argument as an array, and call takes argument individually.

Bind — Use to bind an object method to another object.

const number = {

x: 42,

getX: function() {

return this.x;

}

};

const boundGetX = number.getX.bind(number);

console.log(boundGetX()); // expected output: 42

2. What is Higher Order Component?

Higher order functions are functions that takes a function as argument or can return a function.

3. What is callback?

A JavaScript callback function is a function that is passed as an argument in a function and run inside the function where it is passed. JavaScript Callback Functions can be used synchronously or asynchronously.

4. Why functions are First-class objects?

Functions are treated as any other value in JavaScript. They can be assigned to variables, the can be the properties of an object. They can also be function parameters.

5. Describe async and await in JavaScript?

Async await functions are used for writing asynchronous code in JavaScript. Async makes function asynchronous which means this code will be proceeded all alone. Await makes the program wait to finish one specific piece of code.

6. What is an arrow function?

A function written with an arrow(=>) is called an arrow function.

7. Why ‘this’ is not used in arrow function?

Because for arrow function grabs or gets the ‘this’ value of lexically enclosing function or in this example.

8. What are promises?

Promises are one way in handling asynchronous operations in JavaScript. It represents the value of an asynchronous operation. Promises was made to solve the problem of doing and dealing with async code.

9. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a group of related technologies used to grab data from a source and display data asynchronously.

10. What is constructor?

A constructor is a function that initializes an object. Constructors initializes object values inside a class.

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

Objects and Others

1. What are closures?

Closures are one function wrapping another function and the inner function have the access to the outer function’s variable.

2. Why delete is used in object?

Delete uses to delete properties in an object.

3. How to create an object without an instance?

Using Object.create()

var myObject = {

price: 20.99,

get_price : function() {

return this.price;

}

};

var customObject = Object.create(myObject);

4. What is hoisting?

For var declared values and functions it is hoisted at the top of the function scope so that it can be accessible anywhere inside the function.

5. What is destructuring?

Destructuring is getting the specific value of an index or a key in an array or an object.

Array destructuring: const [a,b]=[1,0,23,14]

Object destructuring: const {name, age}={name:”Raphael”, age: 25}

6. What is the use of set object?

Set object is an ES6 feature that lets you store unique values.

const set2 = new Set([“a”,”b”,”c”,”d”,”d”,”e”]);

It returns a set object.

7. What are the differences between spread and rest operator?

They look like same. But spread operator is used to spread array values to an array.

rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.

8. What are wrapper objects?

Every primitive except null and undefined have Wrapper Objects. The Wrapper Objects are String,Number,Boolean,Symbol and BigInt. Wrapper objects have methods and properties which primitive types can access directly.

9. Difference between a method and a function?

A function can be accessed from anywhere but for a method you need have an object instance created.

10. What is the difference between Object.freeze() and Object.seal()?

Any object passed inside the Object.freeze(), no properties can be added, modified, the object itself cannot be re-initialized. Same for Object.seal() except object properties can be modified.

11. What is the difference between in and hasOwnProperty in objects?

in checks both the object and its prototype chain whether a property is available or not. hasOwnProperty checks only on the object it is called.

12. How to assign properties outside function?

By using prototype property,

function Rectangle(length, width) {

this.length = length;

this.width = width;

}

Rectangle.prototype.getArea = function() {

return this.length * this.width;

};

13. What is prototype based inheritance?

Using the prototype property to inherit properties from another object.

function Rectangle(length, width) {

this.length = length;

this.width = width;

}

Rectangle.prototype.getArea = function() {

return this.length * this.width;

};

function Square(length) {

Rectangle.call(this, length, length);

}

Square.prototype = Object.create(Rectangle.prototype, {

constructor: {

value:Square,

enumerable: false,

writable: true,

configurable: true

}

});

var square = new Square(3);

console.log(square.getArea());

14. Describe classes in JavaScript?

Classes are new Syntax in ES6. It is a new way of writing constructor functions in JavaScript.

For classes, instance should be created to use its properties. There are two ways to create instances. The new keyword and inserting prototype inside object.create().

A class must have a constructor to initialize its object values.

15. What is the use of new Keyword?

new keyword is used to create instances of classes and functions.

--

--

Serajur Reza Chowdhury
Serajur Reza Chowdhury

Written by Serajur Reza Chowdhury

Software Engineer, curious JavaScript programmer, love to share concepts.

No responses yet