Disclaimer: This article was written few years ago and may no longer be relevant as software engineering has changed a lot in the last few years. This is what may be more relevant now: Future of Software Engineering - Gaurav ChandakJavaScript interview questions are commonly asked in Frontend and Fullstack interviews at most product-based companies.
'Top JavaScript Interview Questions and Answers' contains the most frequently asked questions at these companies. These questions and answers will help you prepare for these interviews.
Table of content:
- What is Hoisting in JavaScript?
- What are Callbacks in JavaScript?
- What are Closures in JavaScript?
- What are async functions in JavaScript?
- What is the purpose of constructors in JavaScript?
- What is the difference between '==' and '===' in JavaScript?
- What is the difference between 'null' and 'undefined' in JavaScript?
- What are the different data types in JavaScript?
- What is NaN in JavaScript?
- What are var, const, let keywords in JavaScript?
- What is 'strict mode' in JavaScript?
- What are Arrow Functions in JavaScript?
- What is Object Destructuring in JavaScript?
- What is the Spread Syntax or Spread Operator?
- What is the Rest Syntax or Rest Operator?
- What are Higher-order functions in JavaScript?
- What is the difference between map() and forEach() in JavaScript?
- What is Immediately Invoked Function Expression (IIFE) in JavaScript?
- What is the purpose of the 'this' operator in JavaScript?
- What are Promises in JavaScript?
- What are events in JavaScript?
- What are setTimeout and setInterval methods in JavaScript?
- What is debouncing and throttling in JavaScript?
- What is event bubbling in JavaScript?
- What are the different scopes in JavaScript?
- What is Scope Chain in JavaScript?
- What are function prototypes in JavaScript?
- What are call(), apply() and bind() methods in JavaScript?
- How do you create a polyfill for the bind() function?
- What is HTML DOM?
- What is the difference between window and document in JavaScript?
- What is Event Loop in JavaScript?
- What is Callback Queue in JavaScript?
- What is Type Coercion in JavaScript?
- What is Currying in JavaScript?
- What is the difference between 'async' and 'defer' attributes?
- What is Temporal Dead Zone in JavaScript?
- What is Object Flattening in JavaScript?
- What are iterators and generators in JavaScript?
- What is Prototypal Inheritance (prototype chain) in JavaScript?
1. What is Hoisting in JavaScript?
Hoisting in JavaScript is the behavior by which the declaration of variables and functions are moved to the top. This means that the variable or function declaration need not be done before initializing and calling them.
Hoisting will happen only if var is used for declaration and not with const or let declarations. To avoid hoisting in JavaScript, the strict mode can be used.
Example (Variable Hoisting)
Without Hoisting:
var num = 5; // num is declared and then initialized
console.log(num); // num is calledWith Hoisting:
num = 5; // num is initialized
console.log(num); // num is called
var num; // num is declared after initializing it. During execution, this will be moved to the topExample (Function Hoisting)
Without Hoisting:
function functionName() {
console.log("workattech");
}
functionName(); // function is called after declaring itWith Hoisting:
functionName(); // function is called before declaring it
function functionName() {
console.log("workattech");
}2. What are Callbacks in JavaScript?
Callbacks are functions that can be passed as an argument to another function. The callback function can be called from the function to which it was passed (caller) after some event has happened. A common use case of a callback function is to call it after some asynchronous processing has occurred inside the caller function.
Example
function square(number) {
console.log(number * number);
}
function mainFunction(callback) {
const number = 5;
callback(number);
}
// This function call will print 25
mainFunction(square);In the above example, the function 'square' was a callback function since it was passed as an argument to the mainFunction and was executed after that.
3. What are Closures in JavaScript?
The ability of a function to access variables and functions that are lexically out of its scope are called closures. Closures are created whenever new functions are created and have references to their surrounding states.
Example
function welcome() {
const name = 'workattech'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
welcome();In the above example, the function displayName can access the variable 'name' which is declared outside the function.
4. What are async functions in JavaScript?
Async functions are those functions using which asynchronous, promise-based behavior can be introduced without explicitly using a Promise.
The 'await' expression is used along with the async functions. An async function can have zero or more await expressions. await is used to make the function appear to be synchronous until the promise is fulfilled or rejected.
Example
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('workattech');
}, 2000);
});
}
async function asyncCall() {
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall(); // calling the async function asyncCall() will output workattech after 2 seconds5. What is the purpose of constructors in JavaScript?
Constructor is used in JavaScript to create objects with similar properties and methods. While creating a constructor function, the name of the function should start with a capital letter. The 'new' keyword is used to create a new object.
Example
function Student(name, age, mark) {
this.name = name;
this.age = age;
this.mark = mark;
}
const studentOne = new Student('Elon', 50, 98);
const studentTwo = new Student('Mark', 37, 97); In the above example, the function Student is the Constructor function as it is used to create multiple objects of the same properties.
6. What is the difference between '==' and '===' in JavaScript?
The abstract equality operator (==) and strict equality operator (===) are both comparison operators. The '===' can be used to compare both values and types whereas '==' can be used to only compare values.
Example
const x = 0;
const y = '0';
console.log(x === y); // false
console.log(x == y); // true7. What is the difference between 'null' and 'undefined' in JavaScript?
undefined is a primitive value that is assigned to a variable before it is initialized. In other words, if you declare a variable but don't initialize the value, it will appear to be undefined during code execution.
The value 'null' can be assigned to any variable. It represents that the variable has no value.
Examples
null:
const x = null;
console.log(x); // nullundefined:
let x;
console.log(x); // undefined8. What are the different data types in JavaScript?
Number: It is a double-precision 64-bit binary format value that can represent any number. There is no concept of int/float in JS. Every number is a 64-bit floating-point number.
Example
const x = 1; Boolean: It can have only two values and represents a logical entity. The two values are true and false.
Example
const x = 0;
const y = 1;
const z = 1;
x == y; // returns false
y == z; // returns trueString: It is used to represent textual data. It can be represented using a pair of single-quotes or double-quotes.
Example
const name = 'workattech';BigInt: It is used to represent the numbers that are greater than those that can be represented using the Number data type.
Example
const bigInteger = 2234567899876543212345678987654321223;Null: It is used to represent the intentional absence of a variable value.
Example
const userName = null;undefined: The value undefined is assigned to a variable if it has not been initialized. The type of undefined is also undefined.
Example
const userName;
const userAge = undefined;The above data types represent primitive data types. To store any non-primitive data, we have objects in JavaScript. Any kind of data structure that we need to create can be done through objects.
Example
const user = {
name : 'Elon',
age : 50,
isActive : true,
};
console.log(user.name + " " + user.age + " " + user.isActive); // Elon 50 true9. What is NaN in JavaScript?
NaN (Not-a-Number) is a JavaScript property used to represent values that are not proper numbers. NaN is returned by numerical operations where the operation is unable to resolve a numerical value.
Examples
parseInt("workattech");
Math.sqrt(-1);
"workattech"/3The isNaN() function can be used to check whether a value is NaN or not. While using the isNaN() function, the value will be first converted to a Number type. Then a check would happen to find out whether it is NaN or not.
Examples
isNaN(123); // false
isNaN('workattech'); // true
isNaN('123'); // false → '123' is converted to Number type (123) and hence it is NaN
isNaN(undefined); // true
isNaN(true); // false → true is corresponding to 1, which is converted to Number type and checked
isNaN(false); // false10. What are var, const, let keywords in JavaScript?
var, const, and let are the keywords that can be used to declare the variables in JavaScript.
Scopes:
- The '
var' keyword is globally and functionally scoped and it can be re-assigned. - The '
let' keyword has functional and block scope and can also be re-assigned. - The '
const' keyword also has functional and block scope but it cannot be re-assigned.
Note that let can be used everywhere instead of const. A good practice to avoid bugs is to use const by default and use let when we are sure that the variable might get updated. Such bugs easily come up in large codebases.
Using the best practices ensures that we can avoid such bugs. We prefer to use const and let instead of var since not having a block scope can result in unexpected bugs.
11. What is 'strict mode' in JavaScript?
Strict mode can be used to enforce the restricted variant of JavaScript along with non-strict mode code or alone. It can be applied to the entire script or individual functions and won't be applicable to block statements enclosed in { }.
Example (strict mode for the entire script)
'use strict';
const name = 'workattech';Example (strict mode for a function)
function user(){
'use strict';
console.log("Strict mode");
}12. What are Arrow Functions in JavaScript?
An arrow function is a modern way to create functions. It helps write compact, concise code.
Example
Let's look at a normal function for adding two numbers:
const add = function(firstNum, secondNum) {
return firstNum + secondNum;
}We can convert it into an arrow function like this:
const add = (firstNum, secondNum) => {
return firstNum + secondNum;
}If the function has only one statement (which is also the return statement) then we can shorten it further like this:
const add = (firstNum, secondNum) => firstNum + secondNum;What we have done here is that we have removed the curly braces and return statement.
13. What is Object Destructuring in JavaScript?
Object Destructuring or destructuring assignment is an approach by which the properties from an object or values from an array can be directly unpacked to different variables.
Example (Without Object Destructuring)
const course = {
name: 'Introduction to JavaScript',
isPaid: true,
cost: {
amount: 999,
currency: 'INR'
}
};
const name = course.name;
const isPaid = course.isPaid;
const cost = course.cost;
console.log(name); // Introduction to JavaScript
console.log(isPaid); // true
console.log(cost); // { amount: 999, currency: 'INR' }Example (With Object Destructuring)
const course = {
name: 'Introduction to JavaScript',
isPaid: true,
cost: {
amount: 999,
currency: 'INR'
}
};
const { name, isPaid, cost } = course; // destructuring is done here
console.log(name); // Introduction to JavaScript
console.log(isPaid); // true
console.log(cost); // { amount: 999, currency: 'INR' }Example (With Object Destructuring and having alias for properties)
const course = {
name: 'Introduction to JavaScript',
isPaid: true,
cost: {
amount: 999,
currency: 'INR'
}
};
const { name: courseName, isPaid, cost: courseCost } = course;
console.log(courseName); // Introduction to JavaScript
console.log(isPaid); // true
console.log(courseCost); // { amount: 999, currency: 'INR' }Example (Partial Object Destructuring)
const course = {
name: 'Introduction to JavaScript',
website: 'workat.tech',
isPaid: true,
cost: 999
};
const { name, cost, ...rest } = course;
console.log(name); // Introduction to JavaScript
console.log(cost); // 999
console.log(rest); // { website: 'workat.tech', isPaid: true }Example (Array Destructuring)
const nums = [4, 5, 6, 7];
const [first, second, ...rest] = nums;
console.log(first); // 4
console.log(second); // 5
console.log(rest); // [ 6, 7 ]14. What is the Spread Syntax or Spread Operator?
The spread operator/syntax can be used where all elements of an array or object need to be included in a list. The spread operator unpacks all the elements as values that can be used. It can be used through triple dots (...).
Example (Function arguments)
function sum (num1, num2, num3) {
return num1 + num2 + num3;
}
const numbers = [5, 7, 2, 1, 3];
const result = sum(...numbers);
console.log(result); // 14 (5 + 7 +2)Example (Adding elements in array)
let numbers = [5, 7, 2, 1, 3];
numbers = [ ...numbers, 4, 5, 8];
console.log(numbers); // [5, 7, 2, 1, 3, 4, 5, 8]Example (Merging two arrays)
let numbers = [5, 7, 2, 1, 3];
const newNumbes = [4, 5, 8];
numbers = [ ...numbers, ...newNumbers ];
console.log(numbers); // [5, 7, 2, 1, 3, 4, 5, 8]Example (Object destructuring)
const obj = { 'firstName': 'Elon', 'lastName': 'Musk' };
const clonedObject = { ...obj };Example (Object destructuring - new properties)
const obj = { 'firstName': 'Elon', 'lastName': 'Musk' };
const country = 'USA';
console.log({ ...obj, country, companies: ['Paypal', 'Tesla', 'SpaceX'] });15. What is the Rest Syntax or Rest Operator?
The rest parameter or the rest syntax is opposite to the spread parameter in a way. It collects multiple elements (or arguments)and converts them into a single element. They are used in function declarations, array destructuring, and object destructuring.
It can be used through triple dots (...). The rest should be used as the last parameter of the function or as the last variable while destructuring.
Example (Function Arguments)
function myFunction(a, b, ...rest) {
console.log("a", a);
console.log("b", b);
console.log("rest", rest);
}
myFunction("one", "two", "three", "four", "five");Example (Array Destructuring)
let numbers = [5, 7, 2, 1, 3];
numbers = [ a, b, c, ...rest ];
console.log(a); // 5
console.log(b); // 7
console.log(c); // 2
console.log(rest); // [1, 3]Example (Object Destructuring)
const obj = { 'firstName': 'Elon', 'lastName': 'Musk', 'country': 'US', companies:['Paypal', 'Tesla', 'SpaceX'] };
const { firstName, lastName, ...rest } = obj;
console.log(firstName); // Elon
console.log(lastName); // Musk
console.log(rest); // { 'country': 'US', companies: ['Paypal', 'Tesla', 'SpaceX'] }16. What are Higher-order functions in JavaScript?
Higher-order functions are those functions that take other functions as an argument or return them.
Example
function doTask() {
return function() {
console.log("Hello World!")
}
}
const x = doTask();
x();17. What is the difference between map() and forEach() in JavaScript?
The forEach() method iterates over a list (or an array) and carries out some operations on each of the elements.
Example
const array = [1, 2, 3, 4, 5];
array.forEach(element => {
console.log(element);
}); // outputs every element of the arrayThe map() method iterates over a list, applies some callback function to each element, and constructs an array from the results. It does not cause any change in the list on which it was called.
Example
const array = [1, 2, 3, 4, 5];
const map = array.map(element => element*element);
console.log(map); // outputs the square of each element as a new array18. What is Immediately Invoked Function Expression (IIFE) in JavaScript?
Immediately Invoked Function Expression (IIFE) are those functions in JavaScript that run as soon as it is defined. It does not need to be invoked separately. The syntax is similar to an ordinary function, but it is enclosed within parentheses and ends with another set of parentheses. IIFE can be used when a code that won't be used again, needs to be invoked.
Example
(function hello() {
console.log("workattech");
})();19. What is the purpose of the 'this' operator in JavaScript?
In JavaScript, the 'this' keyword inside an object refers to that object itself. It is mainly used in functions and constructors to access the properties and functions of that object.
Example
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName () {
return `${this.firstName} ${this.lastName}`;
}
}
const person = new Person ('Elon', 'Musk');
console.log(person.getFullName()); // Elon Musk20. What are Promises in JavaScript?
Promises in JavaScript allow us to defer a set of actions until a particular action is completed. We do not need to wait for the actions to be completed. We can instead defer the further actions to be done only after the prerequisite action has been done.
Example
- Start making tea and serve tea after it has been made
- Start making breakfast and serve breakfast after it has been made
- Work
We can write the above set of actions like this:
make('tea').then(tea => {serve(tea);});make('breakfast').then(breakfast => {serve(breakfast);});work();
What Promise means is that "I promise to let you know when I'm done". In the above examples, it means "I promise to let you know when making a tea is done.". The consumer can do any action after the promise is fulfilled. Here, the then part will be automatically called once the Promise is completed.
In the above code, we saw how we can add a then block to the promise to handle it on completion. There we looked at only the success scenario. What if the Promise fails. We can send two callbacks to 'then' (one for success and the other for failure) like this:
asyncFunction().then(onSuccess, onError);If we are only interested in the success scenario, we can omit the onError callback and directly write:
asyncFunction().then(onSuccess);What if we are only interested in handling the error and do not want to handle success scenarios?
We can pass null to onSuccess and pass a callback to onError like this:
asyncFunction().then(null, onError);Not a very clean solution, right?
There is a function in the promise object which acts as an alias to the above:
asyncFunction().catch(onError);Note that catch(onError) is the same as then(null, onError). You can consider it just an alias.
21. What are events in JavaScript?
In JavaScript, events are signals generated by an HTML node to denote that something has happened. That something could be anything like clicking, hovering, typing, etc.
These events can be detected and JavaScript enables us to execute certain code (or invoke functions) once they are detected. Each available (detectable) event can have an event handler, which is a block of code that runs when the event fires.
Event handlers can be registered by defining the code to run in response to an event. There are two major ways to handle events. The first one is by using HTML element methods and the second one is by adding event listeners.
Example (Event Handler)
<input
type="button"
id="some-button"
onclick="console.log('Button Clicked')">The addEventListener takes the event and the listener method as parameters. It adds the listener for the event on the object from which it is called.
Example (Event Listener)
<head>
<script>
window.addEventListener('load', () => {
const button = document.querySelector('#some-button');
button.addEventListener('click', event => {
console.log('Button Clicked');that can represent any number
});
const inputField = document.querySelector('#some-text-input');
inputField.addEventListener('change', event => {
console.log(`Text Changed to ${event.target.value}`);
});
inputField.addEventListener('input', event => {
console.log('Text Input');
});
}
</script>
</head>
<body>
<input type="button" id="some-button">
<input type="text" id="some-text-input">
</body>22. What are setTimeout and setInterval methods in JavaScript?
In JavaScript, the setTimeout method takes a callback function and timer as arguments and invokes the callback once the timer expires. It can be used to execute any logic that needs to be done after a particular time.
Example
setTimeout(function() {
console.log('workattech');
}, 2000); // outputs workattech after 2 secondsSimilar to setTimeout, setInterval is also used to execute a function after a delay. The difference here is that the function would be called repeatedly after the mentioned delay.
Example
setInterval(() => {
console.log('workattech');
}, 3000); // outputs workattech after every 3 seconds23. What is debouncing and throttling in JavaScript?
Debouncing and Throttling are programming concepts that can be used to optimize performance in JavaScript. In case multiple events of the same type are occurring, debouncing and throttling allow us to reduce the number of times the event handlers are triggered.
Debouncing
Debouncing works by grouping function calls and calling them only after a predefined amount of time has passed since the last call.
Example
If a page is scrolled, instead of calling the scroll event handler for every scroll event, debounce can help group these calls and call it once after, let's say, 50 milliseconds since the last scroll event. This would keep the scroll smooth without getting affected by the handler.
Throttling
Throttling is a similar concept to debouncing. Throttling works by not allowing any function call for a predefined amount of time after a function call.
Example
If a button is pressed 10 times in a single second, we would not want the event handler to be triggered 10 times as the handling might be expensive. We can use throttling to restrict the event handler from getting triggered for 1 second since the previous trigger.
Debouncing vs Throttling
The major difference between Debouncing and Throttling is that in the case of debouncing the function call would happen only after the last event whereas in the case of throttling the function call can happen after every X milliseconds if continuous events are happening.
24. What is event bubbling in JavaScript?
Assume that an HTML element is present inside another element (parent element) and both of them have their event handlers. In this scenario, if an event happens on the child element, the event handler of the child element will handle it first followed by the event handler of the parent element. This principle is called event bubbling in JavaScript.
Example
<form onclick="alert('form : parent')">form : parent
<div onclick="alert('div : child of form')">div : child of form
<p onclick="alert('p : child of div')">p : child of div </p>
</div>
</form>In the above example, if the p element is clicked then its event handler will be invoked followed by the handler in div followed by the handler in form.
25. What are the different scopes in JavaScript?
In JavaScript, scope gives the context about the accessibility of a variable or function in the code. There are three types of scope based on which a function or a variable can be accessed. They are:
- Global Scope
- Function/Local Scope
- Block Scope
Global Scope
The variables or functions that are declared in the global scope can be accessed anywhere in the code.
Example
const name = 'workattech';
function printName() {
console.log(name);
}
printName(); // outputs workattechFunction/Local Scope
The variables or functions that are defined in the function/local scope can be accessed only within that function and not outside it.
Example
function printName() {
const name = 'workattech';
console.log(name); // outputs workattech
}
console.log(name); // throws an error as the variable name cannot be accessed outside the functionBlock Scope
The variables that are defined using let and const inside a { } (block) cannot be accessed outside that block. Block scope is not applicable for the variables defined using var.
Example
let x = 5;
if(x === 5) {
const a = x;
console.log(a); // outputs 5
}
console.log(a); // throws an error26. What is Scope Chain in JavaScript?
During execution, if a variable or a function cannot be found inside a scope, the JavaScript engine searches for them in the outer scope. If the outer scope is also not having the variable or the function, the global scope will be searched. This entire chain of scopes (from the current scope to the global scope) is called the scope chain in JavaScript. If the variable or the function is not found in the global scope, a reference error is thrown.
Example
const stringOne = 'I am from the global scope';
function one() {
const stringTwo = 'I am from the outer scope';
function two() {
const stringThree = 'workattech';
console.log(stringThree); // outputs workattech
console.log(stringTwo); // outputs I am from the outer scope
console.log(stringOne); // outputs I am from the global scope
console.log(stringZero); // throws reference error as stringZero is not present in any of the scope
}
two();
}
one();27. What are function prototypes in JavaScript?
In JavaScript, the function prototype can be used to add new properties to any function at a later stage. It can then be accessed by all the instances of that function. It is an object that is associated with every function by default.
Example
without function prototype:
function Course() {
this.name = 'Learn to Code';
this.price = '699';
}
const courseObjectOne = new Course();
courseObjectOne.status = 'Active';
const courseObjectTwo = new Course();
courseObjectTwo.expiry = '4 months';
console.log(courseObjectTwo.status + " - Access for " + courseObjectOne.expiry); //outputs undefined - Access for undefinedIn the above example, the new property 'status' is added to the courseObjectOne. But it cannot be accessed (undefined) by courseObjectTwo. Similarly, the 'expiry' property which was added to courseObjectTwo cannot be accessed (undefined) by courseObjectOne.
with function prototype:
function Course() {
this.name = 'Learn to Code';
this.price = '699';
}
Course.prototype.status = 'Active';
const courseObjectOne = new Course();
Course.prototype.expiry = '4 months';
const courseObjectTwo = new Course();
console.log(courseObjectTwo.status + " - Access for " + courseObjectOne.expiry); //outputs Active - Access for 4 monthsIn the above example, the new properties are directly set to Course at a later stage, using the prototype property. As a result, the new properties can be accessed by all the instances of Course.
28. What are call(), apply() and bind() methods in JavaScript?
call() Method
The call() is a method in JavaScript that helps us to call a function with a given object as the 'this' value. The call() method takes all the arguments individually.
Syntax
functionName.call(thisArgument, ...functionArgs);Example
const personOne = {
firstName : "Elon",
secondName : "Musk"
}
const getFullName = function(company, country) {
console.log(this.firstName + " " + this.secondName + ", " + company + ", " + country);
}
const personTwo = {
firstName : "Mark",
secondName : "Zuckerburg"
}
getFullName.call(personOne, "Tesla", "United States"); // outputs Elon Musk, Tesla, United States
getFullName.call(personTwo, "Facebook", "United States"); // outputs Mark Zuckerberg, Facebook, United Statesapply() Method
The apply() method is similar to the call() method. The only difference is that the apply() method takes an array as the argument whereas they were taken individually as arguments in the case of the call() method.
Syntax
functionName.apply(thisArgument, functionArgsArray);Example
const personOne = {
firstName : "Elon",
secondName : "Musk"
}
const getFullName = function(company, country) {
console.log(this.firstName + " " + this.secondName + ", " + company + ", " + country);
}
const personTwo = {
firstName : "Mark",
secondName : "Zuckerburg"
}
getFullName.apply(personOne, ["Tesla", "United States"]); // outputs Elon Musk, Tesla, United States
getFullName.apply(personTwo, ["Facebook", "United States"]); // outputs Mark Zuckerberg, Facebook, United StatesIn the above example, the company and country parameters were passed as a single array. It was passed individually in the case of the call() method.
bind() Method
The bind() method is used to create a new function from another function with a given object as the this argument. It creates a copy of the function and then binds it to the object for which it was called. It does not immediately invoke the function and the new copy needs to be invoked separately.
Example
const personOne = {
firstName : "Elon",
secondName : "Musk"
}
const getFullName = function(company, country) {
console.log(this.firstName + " " + this.secondName + ", " + company + ", " + country);
}
const getPersonOneDetails = getFullName.bind(personOne, ["Tesla", "United States"]);
getPersonOneDetails(); // outputs Elon Musk, Tesla, United StatesIn the above example, calling the bind method on 'getFullName' creates a copy of it, which is assigned to 'getPersonOneDetails'. When the 'getPersonOneDetails' is called separately, we will get the desired output.
29. How do you create a polyfill for the bind() function?
Polyfill is a way to implement a JavaScript feature not supported by older web browsers. Using polyfill, new features can be made available on the older versions. Let us look at how we can implement the functionality of a bind() function.
Polyfill
Function.prototype.customBind = function (thisArg, ...args) {
const fn = this;
return function (...fnArgs) {
fn.apply(thisArg, [...args, ...fnArgs]);
}
}Example
Function.prototype.customBind = function (thisArg, ...args) {
const fn = this;
return function (...fnArgs) {
fn.apply(thisArg, [...args, ...fnArgs]);
}
}
const personOne = {
firstName : "Elon",
secondName : "Musk"
}
function printFullName(company, country) {
console.log(this.firstName + " " + this.secondName + ", " + company + ", " + country);
}
// Here, we are creating a new function by calling customBind on printFullName
const printPersonOneDetails = printFullName.customBind(personOne, ["Tesla"]);
printPersonOneDetails("United States");30. What is HTML DOM?
The Document Object Model (DOM) represents the structure of a document with which the web pages can be connected to programming languages or scripts. The document is represented with a logical tree. Each branch of the tree ends in a node and each node contains objects. The structure, style, or content of the document can also be changed. The nodes can have event handlers attached to them that can respond to events.
31. What is the difference between window and document in JavaScript?
The window interface is the root level element containing a DOM document. The global variables are defined on the window object. Methods like alert() and confirm() are defined on this object. It also has properties like the document, location, etc. Each browser tab has its window object.
The document is the child of the window object. It is the main object of the DOM (Document Object Model). The document can be accessed via window.document or document. The document object also has many useful methods like document.getElementById(), document.createElement(), document.querySelector(), etc.
32. What is Event Loop in JavaScript?
JavaScript is a single-threaded, synchronous language. To make asynchronous processing possible, browsers have a process known as an event loop.
The browser contains the JavaScript call stack, an event queue, and Web APIs. Every function call is added to the call stack till its execution is completed. In the case of asynchronous code, we would not want to get blocked on it. This is handled by the Web APIs which allow asynchronous processing possible. The async call information is popped from the call stack even before the execution is completed and is taken by the Web APIs. The Web APIs move it to the event queue after processing. The event queue pushes the elements inside it to the call stack again after which the call stack calls the callback of the async function.
This entire process of making asynchronous processing possible by the browsers is known as an event loop.
33. What is Callback Queue in JavaScript?
When asynchronous functions get called, they are added to the callback queue. It is a queue that follows the execution order of First In First Out (FIFO). In the event loop, it is first checked whether the call stack is empty or not. If the call stack is not empty, the functions on that stack will be executed.
If the call stack is empty, the callback queue is checked whether it is empty or not. If there are any functions in the callback queue, it is then executed in the FIFO order. The functions in the callback queue will be executed only if the call stack is empty and the program reaches the end.
34. What is Type Coercion in JavaScript?
Type coercion is the conversion of values from one data type to another. It is similar to type conversion, but type coercion takes place implicitly.
Example
const value1 = 1;
const value2 = '2';
const sum = value1 + value2;
console.log(sum); // 12In the above code, because of the + operator on a number and a string, the number (value1) is implicitly converted to a string. The + operator then acts as a concatenation operator on the two strings.
35. What is Currying in JavaScript?
Currying is a feature in JavaScript that can be used to convert a function having multiple arguments into multiple functions having a single argument. Instead of taking in all the arguments together, the function takes in one argument, which returns a function taking in another argument, which again returns a function that takes in another argument, and so on until all the arguments are fulfilled.
Example
With currying:
function multiply(a) {
return (b) => {
return (c) => {
return a*b*c;
}
}
}
console.log(multiply(5)(6)(7)); // 210Without currying:
function mul(a, b,c) {
return a*b*c;
}
console.log(mul(5,6,7)); // 210It uses the feature of closures using which a function can access variables that are lexically out of its scope and thereby helps to avoid passing the same variables again and again.
36. What is the difference between 'async' and 'defer' attributes (used along with script tag)?
When a browser or a web page loads and starts to build the DOM, the <script> tags block the process to load the JavaScript files, which then have to be executed.
defer
When the defer attribute is used on the <script> tags, all the JavaScript files will get loaded in the background without stopping the processing of HTML, thereby building the DOM and making the content visible quickly. All the loaded scripts will be executed when the DOM has been built.
async
When the async attribute is used on the <script> tag, the JavaScript files will load in the background without blocking the processing of HTML. But, the scripts using async don't depend on anything and get executed as soon as they are loaded.
The main difference between 'defer' and 'async' is that scripts loaded with defer attribute wait till the DOM is built and also follow the original order. In the case of async, once the scripts load in the background, it gets executed irrespective of their order of use.
37. What is Temporal Dead Zone in JavaScript?
If we try to access a variable before it is declared, a reference error will be thrown. It means that the value of the variable cannot be accessed since it is in the temporal dead zone. This is applicable only for let and const. In the case of var, the default value 'undefined' will be shown.
Example
let totalPrice = coursePrice * 1.18; //---------
// | ------> this is TDZ for coursePrice
// |
console.log(totalPrice); //---------
let coursePrice = 699;The above example throws a reference error since the variable was called before it was declared.
38. What is Object Flattening in JavaScript?
Example
const course = {
name: 'Introduction to JavaScript',
isPaid: true,
cost: {
amount: 999,
currency: 'INR'
}
};
const flattenObject = (object) => {
let res = {};
for (const [key, value] of Object.entries(object)) {
if (typeof value === 'object') {
for (const [internalKey, internalValue] of Object.entries(value)) {
res[key + "." + internalKey] = internalValue;
}
} else {
res[key] = value;
}
}
return res;
}
console.log(flattenObject(course));In the above example, 'course' is a nested object. Object flattening converts a nested object into a single object. (This is done by reducing the nesting by one level).
Output
{
name: 'Introduction to JavaScript',
isPaid: true,
'cost.amount': 999,
'cost.currency': 'INR'
}39. What are iterators and generators in JavaScript?
Iterators
An iterator is any JavaScript object that can be used to iterate over a collection of data. An iterator would generally have a next() method using which it can iterate over the data. The next method returns two properties:
- value: the value in the iteration
- done: boolean property signifying the end of the iteration.
After the iteration is completed, the next() method returns { done: true };
Compared to the usual for-loop or while-loop, the loading of the entire data is not required before iterating over it. By using an iterator, only the current position of the element is required.
Example
const courses = ['Learn to Code', 'SDE Kickstart', 'OOP', 'SDE Bootcamp',];
const iterator = courses[Symbol.iterator]();
while (true) {
next = iterator.next();
if (next.done) {
break;
}
console.log(next.value);
}The output of the above program will be:
Learn to Code
SDE Kickstart
OOP
SDE BootcampWe can create our custom iterators as well.
Generators
Generators are functions that can be used to create custom iterators in a simple way.
Generator functions can be created using the function* syntax. It comes with a yield operator which allows us to pause the function until the next value is requested.
The generator function does not initially execute the code but returns an iterator called generator. When a value is used by the generator's next method, the generator function executes until there is a yield keyword. On encountering yield, it outputs the value and pauses the execution until it has to resume the function execution on demand.
Example
function* objects(obj) {
const keys = Object.keys(obj);
for (const key of keys) {
yield [key, obj[key]];
}
}
const courses = {
ltc : 'Learn to Code',
sdeks : 'SDE Kickstart',
oop : 'OOP',
sdebc : 'SDE Bootcamp'
}
for (const [key,value] of objects(courses)) {
console.log(`${key}: ${value}`);
}The output of the above program will be:
ltc: Learn to Code
sdekc: SDE Kickstart
oop: OOP
sddebc: SDE Bootcamp40. What is Prototypal Inheritance (prototype chain) in JavaScript?
Prototypal inheritance is a JavaScript feature using which we can build new methods or objects on top of existing ones. This helps us to use the features of the existing object or method and just add the remaining for the others.
Example
const course = {
status : 'active',
mode : 'self paced'
};
const learnToCode = {
name : 'Learn to Code',
price : '699',
language : 'C/C++'
};
learnToCode.__proto__ = course;
console.log(learnToCode.name + ", is " + learnToCode.mode);The output of the above program will be
'Learn to Code, is self paced'The mode parameter is not directly available on the 'learnToCode' object. Prototypal inheritance helps in accessing the parameters from the main object (which is 'course' above). The 'course' is the prototype of 'learnToCode' (or 'learnToCode' prototypically inherits from 'course'
If a parameter is not present in the object, it is checked on that object's prototype. If it is not found, the prototype of the object's prototype is checked. This will continue until the property is found. This is the prototype chain in JavaScript.
---
I hope that you found this article helpful. You can find best practices, interview preparation tips, and other awesome resources in our resources section.