Top 100 JavaScript Interview Questions and Answers (2023)

Top 100 JavaScript Interview Questions and Answers (2023)

JavaScript is one of the most popular programming languages of 2022. The primary use of JavaScript is for creating interactive Web applications, cross-platform desktop and mobile applications, server-side applications, and whatnot. With the increased popularity of JavaScript, the demand for skilled JavaScript developers has also increased. Every major corporation and many small and large tech startups have a website or Web application updated regularly. Therefore, almost all products and services-based companies require JavaScript developers to manage their websites, web applications, mobile apps, and desktop applications.

JavaScript development is a crowded market, so it’s crucial to know JavaScript, its core concepts, and various techniques to make ourselves stand out.

This article aims to provide 100 JavaScript interview questions that will enhance your chances of landing a JavaScript developer job.

Theoretical questions

Q1. What are first-class functions?

In some programming languages, there is a concept of first-class functions. First-class functions are those treated like ordinary variables. You can assign them to some other variable, pass them as an argument to other functions, and return them from another function.

For example, we can assign a function x to a variable called y.

const y = function x() { console.log('Bar'); }
Code language: JavaScript (javascript)

Q2. What are the function statements and function expressions?

When a function gets created using the function keyword, it’s called a function statement. Assigning a function to a variable is a function expression.

// Function statement function x() { console.log('x'); } // Function expression const y = function () { console.log('y'); }
Code language: JavaScript (javascript)

Q3. What are first-order functions?

A first-order function does not take another function as an argument or return a function.

Q4. What are higher-order functions?

Higher-order functions can accept a function as an argument or return a function as a result.

Q5. What are pure functions?

Pure functions are those whose return values only depend on the arguments they receive. We get the same return value if we call a pure function with the same arguments.

Q6. What is function currying?

Function currying is a process in which we convert a function with multiple parameters to a chain of functions with a single parameter.

// Normal function function sum(a, b) { return a + b; } // Curried function function currySum(a) { return function (b) { return a + b; } } console.log(sum(1, 2)); // 3 console.log(currySum(1)(2)) // 3
Code language: JavaScript (javascript)

Q7. What is prototype chaining?

Prototype chaining is the process of building new objects from old ones. Essentially, it’s like inheritance in a class-based language.

Q8. What is the difference between the null and the undefined values?

Variables get assigned a null value to indicate they are declared and assigned but don’t point to anything. A undefined variable is declared but not initialized.

Q9. What is a strict mode in javascript?

ECMAScript 5 introduced a strict mode that executed the programs and functions strictly. To use strict mode, we write "use strict"; on the top of our JavaScript file.

Q10. What is the difference between == and ===?

The == operator is also called a type-converting equality check operator. When we compare values of different data types, it attempts to do type conversions before checking the equality.

The === operator is also called a strict equality operator. JavaScript engine will make no type conversions in this case.

Q11. What are arrow functions?

An arrow function is a compact way of declaring a function. Functions declared using arrow syntax don’t have this, arguments bindings. First-class cannot use these functions to create a class constructor.

Q12. What is JSON?

JSON stands for JavaScript Object Notation. It stores data in a format similar to JavaScript objects.

Q13. What is hoisting?

Hoisting is the process by which the JavaScript engine sets aside memory for variables, functions, and classes to give the impression that they are at the top of the code.

Q14. What is memoization?

Memoization is a technique that saves calculated results to improve a function’s efficiency. The arguments given to the function serve as the cache object’s key. If a key is present, the function returns the result immediately. Otherwise, the function computes the result, saves it in the cache, and returns it.

Q15. What are closures?

A function bound to its immediate surroundings creates a closure. Essentially, a function defined inside another function is a closure. The variables and operations of the outer function are accessible to the inner function.

Q16. What is scope in JavaScript?

A scope is a code section allowing us to access specific variables and functions. It determines the visibility of variables and functions. Variables and functions declared within a particular scope cannot be accessible outside the scope.

Q17. What is the difference between local storage and session storage?

Both local storage and session storage store data. Local storage persists the data even when we close the browser. In contrast, session storage removes the data when we close the browser tab.

Q18. What is a JavaScript promise?

A promise is a JavaScript object that may or may not produce a value in the future. In other words, the promise object yields a single value when resolved. A promise object can have one of three states: pending, fulfilled, and rejected.

Q19. What is a callback function?

A function passed as an argument to some other function is a callback function. We will invoke the callback function within the function to accomplish the desired result.

Q20. What is callback hell?

Callback Hell is a pattern that consists of multiple nested callback functions. It is an anti-pattern because the code is hard to read and modify.

Q21. What is NaN in JavaScript?

NaN is an abbreviation for “Not a Number.” It represents a value that is not a valid number in JavaScript.

Q22. What is debouncing in JavaScript?

The debouncing technique prevents a function from being called again until a particular time has passed since the last call. Its primary application is in Web application search functionality. The API is called only once per user input.

Q23. How to get the type of a variable?

To know the type of a JavaScript variable, we can use the typeof operator.

const num = 1; const str = 'Hi'; const bool = false; console.log(typeof num); // number console.log(typeof str); // string console.log(typeof bool); // boolean
Code language: JavaScript (javascript)

Q24. Explain the call(), apply(), and bind() methods.

The call() method invokes a function with the specified context and parameters.

const obj = { name: 'varun', greet: function (city) { console.log('Hello ' + this.name + ' from ' + city); }, }; obj.greet('jabalpur'); // Output: // Hello varun from jabalpur const obj1 = { name: 'tarun', }; obj.greet.call(obj1, 'rewa'); // Output: // Hello tarun from rewa
Code language: JavaScript (javascript)

The apply() method invokes a function with the context specified and the arguments provided as an array (or an array-like object). It is similar to call(), except that it accepts parameters in the form of an array.

obj.greet.apply(obj1, ['rewa']); // Output: // Hello tarun from rewa
Code language: JavaScript (javascript)

The bind() method generates a new function that, when called, has this keyword set to the specified context, with a sequence of arguments preceding it. It’s similar to call(), except instead of calling the function directly, it returns a copy of the new function.

Q25. What are the three types of JavaScript errors?

Syntax Error: The syntax of the program is not correct.

Reference Error: The JavaScript Engine cannot find a reference to a variable or function in memory.

Type Error: Trying to reassign a const variable will lead to a Type Error.

Q26. What is the use of this keyword in JavaScript?

In JavaScript, the this keyword points to the object currently referred. The this keyword is widely used to assign values to object attributes in constructors.

Q27. What is the difference between async and defer?

In async, while parsing HTML, the browser fetches the script from the network asynchronously if we encounter a script. After fetching the script, the browser stops parsing HTML and executes the script. After executing the script, the browser resumes the HTML parsing.

In defer, while parsing HTML, the browser fetches the script from the network asynchronously if we encounter a script. The browser executes the scripts only after parsing the HTML.

Q28. What are cookies?

Cookies are small data packets that the server sends to the client. The client stores the cookie inside the browser and sends it to the server on each future request.

Q29. What is the difference between let and var keywords?

Both let and const are used for declaring a variable in JavaScript. The var keyword variables have function scope, while the let keyword variables have block scope.

Q30. What is the difference between let and const keywords?

In JavaScript, both let and const are used to declare a new variable. The main distinction is that variables declared with the const keyword cannot be reassigned.

Q31. Is javascript a dynamic or static language?

JavaScript is a dynamic language.

Q32. What are the different data types in JavaScript?

Number, String, Boolean, NULL, Undefined, and Symbol are the seven primitive data types, but the non-primitive data type “object” is also present.

Q33. What are Immediately Invoked Function Expressions?

An immediately invoked function, often known as an IIFE or IIFY, starts executing instantly after its declaration.

Q34. What is the use of a constructor function in JavaScript?

Constructor functions construct individual objects or groups of objects with similar properties and methods.

Q35. What is a BOM?

BOM stands for Browser Object Model and provides a way for users to interact with browsers using a window object, which is the first object of a browser.

Q36. What are generator functions in JavaScript?

A generator function is declared using the function* keyword. It is a special class of function. Rather than executing the code, it returns a generator object that handles the execution. It is possible to stop the execution of generator functions mid-invocation and resume them from where they left off.

Q37. What is Object Destructuring?

Destructuring is a technique for extracting elements from objects or arrays.

const obj = { name: 'varun', age: 20 }; const arr = [1, 2, 3]; // Destructuring elements from an object const { name, age } = obj; // Destructuring elements from an array const [x, y, z] = arr;
Code language: JavaScript (javascript)

Q38. What is the difference between Prototypal inheritance and Classical Inheritance?

Using prototypal inheritance, we create new objects from existing objects serving as a template. Classical inheritance involves classes that inherit properties and methods from a base class.

Q39. What is a Temporal Dead Zone?

The Temporal Dead Zone is the place where variables declared with let and const are hoisted. Although the variables have space reserved in the memory, we cannot access the variables found in the temporal dead zone. It ends when execution reaches the initialization line, where we may usually access variables.

Q40. How to check whether an object is frozen or not?

The Object.isFrozen() method determines if the object is frozen or not.

Q41. What are primitive data types?

Primitive data types contain only values of only one type. The data types include Boolean, Undefined, Null, Number, and String.

Q42. What is the difference between Event Capturing and Event Bubbling?

Event bubbling begins at the innermost element and propagates outward. On the other hand, event capturing propagates from the outermost element to the innermost element.

Q43. What is a DOM?

DOM stands for Document Object Model. The document object is the representation of the HTML document. You can use it to access and modify HTML content.

Q44. What are classes in JavaScript?

ES6 introduced JavaScript classes. They’re mostly just syntactic sugar that we use on top of the current prototype-based inheritance.

Q45. What are ES modules?

ES modules were first introduced in ES6. A Module is a piece of code that we share between multiple components. ES modules are essentially JavaScript files that export some function or variable; other files may utilize them by importing them.

Q46. Why do we need modules?

Putting all the code in a single JavaScript file is impractical, especially when working in groups. Modules overcome this problem by dividing code into various files known as modules. Using modules facilitates team cooperation since each member may work on a separate module without interfering with the rest of the application.

Q47. What does delete do in JavaScript?

The delete operator is used for deleting an object’s property or key.

Q48. What is the difference between for..in and for..of loops in JavaScript?

Both for..in and for..of loops over a list. The for..of loop iterates over an object and returns the values of its properties, whereas the for..in loop returns the list of keys for the object.

Q49. How to validate JSON in javascript?

The JSON.parse function verifies and parses a JSON document. It parses the JSON string and returns a JavaScript object corresponding to the string if it is valid. Otherwise, it throws an error.

Q50. What is the use of the unshift() method?

In arrays, the unshift method can insert a new element at the start of the list. It gives back the new length of the array.

Q51. What is a unary function in JavaScript?

A unary function only takes one parameter, as the name implies.

Q52. What is the argument object in JavaScript?

The arguments object is an Array-like object that can be accessed from within functions and holds the values of the arguments supplied to that function.

Q53. How to find the number of parameters expected by a function?

We can use the length property with the function’s name to get the number of parameters a function expects.

function doStuff(a, b, x, y) { // Does something } console.log(doStuff.length); // 4
Code language: JavaScript (javascript)

Q54. What are anonymous functions in JavaScript?

An anonymous function does not have a name. Anonymous functions may be assigned to variables or utilized as callbacks.

const doStuff = function () { // Does stuff };
Code language: JavaScript (javascript)

Q55. What is the difference between functions and methods?

Functions are snippets of code that we invoke by their name. We define functions outside of any object. Functions are independent of any object. Methods, on the other hand, are functions saved as an object’s property.

Q56. What are generators in JS?

A generator function is a regular function that uses the yield keyword instead of the return keyword whenever it needs to produce a value. The yield statement pauses the function’s execution while yielding a value to the caller, but it leaves behind enough state for the function to continue up where it left off when it resumes.

Q57. What is event handling in JavaScript?

A user visiting a website may cause numerous events, such as the click event, which occurs when the user clicks someplace on a webpage. Event Handling refers to the process of responding to these events.

Q58. What is an event delegation?

Event delegation is an approach to effectively managing events. Instead of adding an event listener to every identical element, we can add one to a parent element and use the event.target property of the event object to fire an event on a specific target.

Q59. What is the difference between a window and a document object?

The window object is at the top of the DOM structure. It symbolizes a browser window that shows the webpage’s contents. The window object is produced whenever a window appears on the screen to show the page’s contents.

The document object represents a browser-loaded web page. We may access the element in the HTML page by using the document object. We may access the document object by using window.document or simply document.

Q60. How to access the page history stack in Javascript?

The window.history object provides access to the browser’s history stack.

Q61. How do you find the user agent details using JavaScript?

The window.navigator.userAgent object provides the information of the user agent.

Q62. What are accessor functions in JavaScript?

ECMAScript 5 introduced JavaScript accessors. The accessor functions get or set properties on an object. Setters use the set keyword, whereas Getters use the get keyword.

Q63. How to handle errors in JavaScript?

The try-catch block is used to place code that might throw an error. The code is written in the try block, and the errors are handled in the catch block.

Q64. What is the use of promise.all()?

Promise.all takes an array of promises as an argument and resolves it when all promises get fulfilled or when anyone gets rejected.

Q65. What is the use of promise.race()?

Promise.race() takes an array of promises as an argument and resolves to a promise instance that resolves or rejects first.

Q66. What is async/await in JavaScript?

The async and await keywords allow easier writing of asynchronous, promise-based behavior, eliminating the need to configure promise chains explicitly.

Q67. What is the difference between fetch() and XMLHttpRequest() in JavaScript?

Both are APIs provided by the browser to make HTTP requests. One significant difference is that fetch() is a promise-based API that makes it easy to handle asynchronous requests.

Q68. What is a service worker?

A service worker is a JavaScript file running in the background, independent of a web page, and provides functionality that doesn’t require a web page or user input.

Q69. What is throttling in JavaScript?

Throttling restricts the number of times we can call a function within a given time.

Q70. What is the same-origin policy?

The same-origin policy restricts JavaScript from performing requests across domain borders.

Q71. What are template literals in ES6?

Template literals make string interpolation and including variables in a string simpler.

Q72. What is Shadowing in JavaScript?

When a variable declared inside a specific scope shares the same name as a variable declared in an outside scope, variable shadowing occurs. We say that the inner variable shadows the outside variable.

Q73. What is the difference between slice and splice methods?

The slice() function returns a new array containing a copy of the original array’s slice. On the other hand, the function modifies the array’s content in place and may be used to add or delete items from the array.

Q74. What is the use of Intl object?

The Intl object is the ECMAScript Internationalization API domain, which includes language number formatting, string comparison, and date/time formatting.

Q75. What is the difference between a mutable and an immutable object in JavaScript?

A mutable object is one whose state may change after its creation. We cannot change an immutable object’s state after its creation.

Output based

Q1. Guess the output of the given JavaScript code?

for (var i = 1; i <= 5; i++) { setTimeout(() => { console.log(i); }, 1000) }
Code language: JavaScript (javascript)


6 6 6 6 6
Code language: JavaScript (javascript)

We are using the var keyword to declare the i variable. Variables declared with var have a global scope rather than a block scope. After 1 second, the variable’s value is 6, so the number 6 gets printed five times.

Q2. Guess the output of the given JavaScript code?

function sum(x, y) { return x + y; } console.log(sum(5, '1'));
Code language: JavaScript (javascript)

Answer: 51

The arguments passed to the function sum include the number 5 and a string’ 1′. The types of both arguments are different. To do the addition, the JavaScript engine transforms the type of the argument. The argument of type number, i.e., 5, is converted to a string and then concatenated with the string’ 1′, resulting in a string ’51’.

Q3. Guess the output of the given JavaScript code?

let x = 10; const y = x++ + ++x - ++x; console.log(y);
Code language: JavaScript (javascript)

Answer: 9

When using a post-increment operator, x++, the variable’s value gets incremented in the memory, but the variable returns the old value. Whereas, in the case of the pre-increment operator, ++x, the value gets incremented, and the variable returns the new value. Therefore the equation becomes,

y = 10 + 12 - 13
Code language: JavaScript (javascript)

The value of y is 9, and so is the output.

Q4. Guess the output of the given JavaScript code?

const arr = [1, 2, 3, 4]; const [x, y] = arr; console.log(x, y)
Code language: JavaScript (javascript)

Answer: 1 2

The technique used here is destructuring. The first two values of the array, arr, are assigned to the variables x and y.

Q5. Guess the output of the given JavaScript code?

const arr = [1, 2, 3]; console.log(typeof arr);
Code language: JavaScript (javascript)

Answer: object

In JavaScript, all the derived data types always have the type object. Since the prototype of arr is the Object prototype, the type of arr is ‘object.’

Q6. Guess the output of the given JavaScript code?

x(); function x() { console.log('Hey'); }
Code language: JavaScript (javascript)

Answer: Hey

Before code execution begins, functions declared with the function keyword get hoisted, and their value is the original function. We may call the function x before it is declared and receive the same result without any errors or warnings.

Q7. Guess the output of the given JavaScript code?

console.log(1); setTimeout(() => console.log(2), 1000); console.log(3) setTimeout(() => console.log(4), 3000); console.log(5);
Code language: JavaScript (javascript)

Answer: 1 3 5 2 4

The setTimeout method is a browser API. When the setTimeout function is encountered, the browser registers the associated callback, and the execution proceeds. When the setTimeout timer expires, the callback function is pushed to a special callback queue. After the synchronous code completes, the event loop checks to see if the call stack is empty. If the call stack is empty, the event loop pushes one callback from the callback queue to the call stack. We obtain the output of the synchronous console.log statements first, followed by the setTimeout functions.

Q8. Guess the output of the given JavaScript code?

function* greetGenerator() { yield 'Hi'; yield 'Hello'; } const greet = greetGenerator(); console.log(greet.next().value); console.log(greet.next().value);
Code language: JavaScript (javascript)

Answer: Hi Hello

Generator functions are kinds of functions that are specified using the function* keyword. Invocation of these functions can be halted in the middle and restarted from where it left off. When the function finds a yield keyword, it returns the value after it. The generator functions do not return anything; instead, they produce values.

In this case, we first set up the generator function greet and then call its next() method. This method returns the generator function’s next possible value. Because there are two yield statements, it produces the two values one by one.

Q9. Guess the output of the given JavaScript code?

function greet(message) { return new Promise((resolve, reject) => { if (message === 'Hi') resolve(message); else reject('Hmm'); }) } const result = greet('Hello').then((data) => { console.log(data) }).catch((data) => { console.log(data); })
Code language: JavaScript (javascript)

Answer Hmm

The function greet returns a promise that resolves if the message argument is a ‘Hi’ string. Otherwise, the promise gets rejected with the message ‘Hmm.’ Because we gave a ‘Hello’ string as an argument, the promise gets rejected, and the callback corresponding to the catch function gets executed.

Q10. Guess the output of the given JavaScript code?

const me = { name: 'Varun', address: { street: 'xyz', pincode: '123456', } }; const {name, address: {street: pincode, pincode: streetName}} = me; console.log(name, streetName, pincode);
Code language: JavaScript (javascript)

Answer: Varun 123456 xyz

The method employed here to extract values from an object is destructuring. We extract the name and address from me object. Furthermore, we destructured the address and extracted the street and pincode. Finally, we changed the renamed street to pincode and Pincode to streetName.

Q11. Guess the output of the given JavaScript code?

const arr = [...'codedamn']; console.log(arr);
Code language: JavaScript (javascript)

Answer: [‘ c’, ‘o’, ‘d’, ‘e’, ‘d’, ‘a’, ‘m’, ‘n’]

The spread operator in an array translates each character in an iterable, such as a string, to one element. As a result, each character in a string is now a separate element in an array.

Q12. Guess the output of the given JavaScript code?

function sum(x, y) { return x + y; } console.log(typeof sum(1, 2));
Code language: JavaScript (javascript)

Answer: number

The value returned by the sum function when called with arguments 1 and 2 will be 3, which is a number.

Q13. Guess the output of the given JavaScript code?

function compare(obj1, obj2) { if (obj1 === obj2) { return true; } else { return false; } } const result = compare({ name: 'varun' }, { name: 'varun' }); console.log(result);
Code language: JavaScript (javascript)

Answer: False

When we compare two objects with the === operator, we compare the references to those objects. Both objects have different references since they belong to other memory locations.

Q14. Guess the output of the given JavaScript code?

function zero() { return (() => 0)(); } console.log(typeof zero());
Code language: JavaScript (javascript)

Answer number

The zero function returns the value of the immediately invoked function expression. This function returned 0 of type “number.”

Q15. Guess the output of the given JavaScript code?

const set = [...new Set([1, 1, 2, 2, 2, 3, 4])]; console.log(set);
Code language: JavaScript (javascript)

Answer: [1, 2, 3, 4]

In a Set, a value can appear only once.

Coding Questions

Q1. How do we unregister a timeout created using setTimeout?

clearTimeout is used to un-register a timeout created using the setTimeout function. It accepts a timeout ID returned while registering a new function using setTimeout.

const timeout = setTimeout(() => { console.log('Hi'); }, 1000); clearTimeout(timeout);
Code language: JavaScript (javascript)

Q2. How do we unregister an interval created using setInterval?

clearInterval is used to unregister an interval created using the setInterval function. It accepts an interval ID returned while registering a new interval using setInterval.

const interval = setInterval(() => { console.log('Hi'); }, 1000); clearInterval(interval);
Code language: JavaScript (javascript)

Q3. How will you check whether a variable is an array?

We may use the operator to check whether the given value is an array.

const arr = [1, 2, 3] const str = 'Hi'; console.log(arr instanceof Array); // true console.log(str instanceof Array); // false
Code language: JavaScript (javascript)

Q4. How do you define a default parameter in a function?

In ES6, we can define a default parameter by assigning it a value using the = operator,

// y is the default parameter function add(x, y = 3) { return x + y; } console.log(add(1)); // 4 console.log(add(1, 2)); // 3
Code language: JavaScript (javascript)

Q5. Write a function deepCopy that takes an object as an argument and returns a copy of it.

function deepCopy(obj) { let object = {}; for (let key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { object[key] = deepCopy(obj[key]); } else { object[key] = obj[key]; } } return object; }
Code language: JavaScript (javascript)

Q6. Write a function deepCompare that takes two objects as an argument and compares them.

function deepCompare(obj1, obj2) { return JSON.stringify(obj1) === JSON.stringify(obj2); }
Code language: JavaScript (javascript)

Q7. Write a function to generate a random number within a given range provided as an argument.

function random(x, y) { return Math.floor(Math.random() * y + x); }
Code language: JavaScript (javascript)

Q8. Write a function that transforms a given string into a camel case.

function toCamelCase(string) { const arr = string.split(' '); const upperCase = arr.map((x, i) => { if (i === 0) return x; else return x.charAt(0).toUpperCase() + x.slice(1); }) return upperCase.join(''); }
Code language: JavaScript (javascript)

Q9. Write a function that returns a debounced version of a given function.

const debouncingFunction = function (fn, delay) { let timeout = null; return function () { let context = this; let args = [...arguments]; clearTimeout(timeout); timeout = setTimeout(function () { fn.apply(context, args); }, delay); }; };
Code language: JavaScript (javascript)

Q10. Write a function that removes duplicates from an array without using Set.

function removeDuplicates(arr) { return arr.filter((x, i) => arr.indexOf(x) === i); }
Code language: JavaScript (javascript)


This article discussed the top 100 most crucial JavaScript Interview questions. These questions will help you ace your technical interview and land your dream job as a JavaScript developer.

Thank you so much for reading ?

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.


No comments so far