Having the right team in place is key to an organization's success. But hiring well-qualified candidates can be an overwhelming process.

Let’s say you have sorted through resumes and narrowed down your top applicants. You are now ready to begin the interview phase. On the other hand, maybe you have diligently prepared your resume and developing skills for the JavaScript technical interview you just landed. Congrats! If you have landed here, then you are headed in the right direction.

From either perspective, the better prepared you are for the interview, the higher your chance of succeeding. We understand that preparing for interviews can be time-consuming. For your convenience, we have compiled a list of the most frequently asked JavaScript interview questions to help find (or be) the right candidate for the position.

Download Now: An Introduction to Java & JavaScript

Table of Contents

Companies may expect different levels of knowledge from junior developers than seniors.

In this guide, we break down the most common JavaScript interview questions into three sections ranging from beginner to advanced — additionally, we've included some common coding practice questions.

Beginner-Level JavaScript Interview Questions 

1. What are the different data types in JavaScript?

JavaScript data types include: String, Number, Boolean, Undefined, Null, Symbol, Objects, BigInt.

2. What is a variable?

Variables are used to store data that will be used in the program. It can point to different values such as numbers, strings, arrays, objects, and functions.

3. Describe local and global variables?

Local variables can be accessed only within the function or block in which they are defined. Global variables can be accessed globally in the entire program (window).

4. What is the difference between "let" and "const"?

Both are used for variable declaration. Let allows the value of the variable to be reassigned. Const doesn’t allow the value of the variable to be reassigned.

5. Name some of the different data structures?

JavaScript data structures include Arrays, Queues, Linked List, Trees, Graphs, and Hashtable/map.

6. Define an anonymous function.

An anonymous function can be defined in a similar way as a normal function but it would not have a name.

7. What is the difference between == and === operators?

== (called loose equal) is used for comparison between two variables regardless of the datatype of the variable. === (called strict equal) is used for comparison between two variables but this will check strict type, which means it will check the data type and compare two values.

Example:

 42 == '42'; // true

 42 === '42'; // false

 42 === 42; // true;

8. What is the difference between synchronous and asynchronous?

Synchronous tasks are performed one at a time and only when one is complete. Asynchronous tasks allow you to move to another task before the previous one finishes.

9. What is isNaN and what does it return?

isNaN stands for "not a number." The function returns true if the value equates to NaN. Otherwise, it returns false.

10. What is a constructor function()?

A constructor function() is a function that creates an instance of a class. We can create several objects of the same type by using an object constructor function.

11. What is a dictionary?

A dictionary stores groups of objects. It has a set of keys and each key has a single associated value.

12. What is a loop and give an example?

A loop invokes the idea of doing some repeating action for each element in a collection. Use a for loop when you know exactly how many times you want the loop to run. Use a while loop to run an indeterminate amount of times.

13. What is the "this" keyword in JavaScript?

The "this" keyword is a self-reference for JavaScript objects. Simply put, it’s a way to refer to the current object within the class definition itself.

14. What does the call() method do?

The call() method can be used to call a method of an object on another object.

15. What is the apply() method?

The apply() method does the same as the call() method. The difference is that apply() method accepts the arguments as an array.

16. What is a callback function in JavaScript?

A callback function is a function that is passed as an argument to another function. This function is executed inside the function to which it’s passed as to “call back” when some action has been completed.

17. What is a promise in JavaScript and why use them?

A promise is an object that may produce value in the future. It is always in one of the possible states: fulfilled, rejected, or pending. Promises provide an alternative approach for callbacks by reducing the callback and writing the cleaner code.

18. Explain what a double exclamation does in JavaScript.

The double exclamation converts anything to a boolean in JavaScript.

19. What are JavaScript events and give an example?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. An example of an event is when the user clicks a button or closes a window triggering an event to happen.

20. What is JSON and why is it used?

JSON (JavaScript Object Notation) is a lightweight data format used to exchange data.

21. What is a closure?

A closure is a function that has access to variables and references outside of its standard scope.

22. What is recursion?

In recursion, a function calls itself multiple times to iterate over an operation. It makes the output easier.

23. Explain "DOM" in JavaScript. What is it used for?

DOM in JavaScript stands for Document Object Model. It is a way to interact with HTML document elements via JavaScript. When the web page is loaded, the browser generates its Document Object Model, and it is constructed as a tree of objects. DOM helps to dynamically change the HTML elements and CSS properties.

24. What is the arrow function?

The arrow function allows you to write a shorthand version of a function definition.

Example:

 fun=()=> "hello"

25. Explain the escape character and give an example.

The escape character is a symbol used to start an escape command in order to perform an activity.

Here are some examples of escape characters:

  • \n = new line
  • \b = backspace
  • \\ = backslash
  • \” = double quote
  • \’ = single quote
  • \t = horizontal tabulator
  • \v = vertical tabulator

26. What is the event.preventDefault method?

The event.preventDefault() method prevents the browsers’ default action like clicking on the link redirecting you to a new page.

27. Explain import and export keywords.

These keywords are used to import and export the data members and member functions from and to different JavaScript files.

28. What is a prototype?

A prototype is a characteristic of an object. It describes the attributes associated with it. It acts as a blueprint of an object.

29. Explain the use of the debugger keyword.

The debugger keyword stops the execution before the next instruction executes in the browser.

30. Describe the various ways to create an array object in JavaScript.

Here are three ways to create an array object in Javascript:

  • Create an instance of an array.

 var exArray = new Array();

  • Use an array constructor.

 var exArray = newArray("hire","Trio","developers");

  • Use an array literal.

 var exArray = ["hire","Trio","developers"];"

31. What ways are there to access properties of an object?

You can access properties of an object in the following ways:

  • Dot notation
  • Bracket notation
  • Expression notation

Advanced-Level JavaScript Interview Questions

32. Explain the role of promises in JavaScript.

There are three different states of a promise object:

  • Pending state: The initial state of promise represents that a promise is pending, neither fulfilled nor rejected.
  • Fulfilled state: This state of promise represents that it has already been fulfilled, with the async operation complete.
  • Rejected state: This promise represents that it has been rejected with the async operation failed.

33. Describe the difference between a cookie, localStorage, and sessionStorage.

Cookie, localStorage, and sessionStorage, are all used to store information. A cookie is a small text file that stores and remembers the user’s data on the local machine. The localStorage will store the data on your local machine and has no expiration time. The sessionStorage only lasts for the session, meaning that all the data stored in sessionStorage will be wiped out on browser close.

34. What is the difference between viewState and sessionState?

In JavaScript, viewState is used for client-side state management, whereas sessionState is used for server-side state management.

35. What is hoisting?

Hoisting is the default behavior in JavaScript, which moves all declarations to the top of the scope before code execution.

36. What is the meaning of a race method in promises?

promise.race() method returns the promise which is resolved or rejected first.

37. What is event bubbling?

In event bubbling, an event starts by running the event handlers on the innermost element. Then it triggers the parents’ event handlers until it reaches the outermost element.

38. How do timers work in JavaScript?

Timers are used to execute a piece of code at a given time or repeat code at a given interval. This is done using the setTimeout, setInterval, and clearInterval functions.

39. How do you read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript:

  • Using JavaScript extensions
  • Using File System Access API and HTML input element

40. What are the three phases of event propagation?

The three phases of event propagation are:

  • Capturing
  • Target
  • Bubbling

41. What does implicit type coercion do?

Implicit type coercion means a value is converted from one type to another under the hood. This takes place when the operands of expressions are of different types.

42. Is JavaScript statically or dynamically typed language? What does this mean?

JavaScript is dynamically typed. This means the type of objects is checked during run-time. (In a statically typed language, the type is checked during compile-time.)

43. What is the spread operator in JavaScript?

Spread operator allows iterables (arrays / objects / strings) to be expanded into single arguments/elements.

44. How do you handle exceptions in JavaScript?

If an expression throws errors, you can handle them with the try…catch statement.

45. What is web storage?

Web storage is an API that provides a way for browsers to store key-value pairs to the user’s browser locally. Using web storage makes this process way more intuitive than using cookies.

Web storage provides two ways of storing data:

  • Local storage: stores data for the client without an expiration date.
  • Session storage: stores data for only one session. The data is gone when the browser is closed.

46. What are modules?

Modules are units of reusable code. Usually, you can import a useful function or constructor to your project from the module.

47. How can you convert a JSON string to a JSON object?

When you receive data from a server, it’s always in a string format. To convert a JSON string to a JavaScript object, use the JSON.parse() method.

48. What is the difference between Document load vs DOMContentLoaded?

The DOMContentLoaded event is triggered when the HTML document has been loaded and parsed. It does not wait for the assets (such as stylesheets and images). The Document Load event triggers only after the full page has loaded, including all the assets.

49. What is a pure function?

A pure function is a function that returns the same result with the same arguments regardless of when and where it’s called. A function is pure if it does not depend on the state, or data change during a program’s execution.

50. What is object destructuring?

Object destructuring is a way to extract properties from an object (or an array).

51. What is an API?

An API stands for Application Programming Interface. APIs are used to allow communication between different applications and parts of the application

Common Coding Problems

52. What will the code below output to the console?

  for (var i = 0; i < 3; i++) {
 setTimeout(() => console.log(i), 1);
}

for (let i = 0; i < 3; i++) {
 setTimeout(() => console.log(i), 1);
}

Answer:

 3 3 3 and 0 1 2

Because of the event queue in JavaScript, the setTimeout callback function is called after the loop has been executed. Since the variable i in the first loop was declared using the var keyword, this value was global. During the loop, we increment the value of i by 1 each time, using the unary operator ++. By the time the setTimeout callback function was invoked, i was equal to 3 in the first example.

In the second loop, the variable i was declared using the let keyword: variables declared with the let (and const) keyword are block-scoped (a block is anything between { }). During each iteration, i will have a new value, and each value is scoped inside the loop.

53. What will the code below output to the console?

 let c = { greeting: 'Hey Reader!' };
let d;

d = c;
c.greeting = 'Hello Reader';
console.log(d.greeting);

Answer:

 Hello Reader

In JavaScript, all objects interact by reference when setting them equal to each other.

First, variable c holds a value to an object. Later, we assign d with the same reference that c has to the object.

When you change one object, you change all of them.

54. What will the code below output to the console?

 function Person(firstName, lastName) {
 this.firstName = firstName;
 this.lastName = lastName;
}

const jim = new Person('Jim', 'Farrey');
const brad = Person('Brad', 'Zitt');

console.log(jim);
console.log(brad);

Answer:

 Person {firstName: "Jim", lastName: "Farrey"} and undefined

For Brad, we didn't use the new keyword. When using new, this refers to the new empty object we create. However, if you don't add new, this refers to the global object.

We said that this.firstName equals "Brad" and this.lastName equals "Zitt". What we actually did, is define global.firstName = 'Brad' and global.lastName = 'Zitt'. Brad itself is left undefined since we don't return a value from the Person function.

55. What will the code below output to the console?

 function sum(a, b) {
 return a + b;
}

sum(1, '2');

Answer:

 "12"

JavaScript is a dynamically typed language: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called implicit type coercion. Coercion is converting from one type into another.

In this example, JavaScript converts the number 1 into a string, in order for the function to make sense and return a value. During the addition of a numeric type (1) and a string type ('2'), the number is treated as a string. We can concatenate strings like "Hello" + "World", so what's happening here is "1" + "2" which returns "12".

56. What will the code below output to the console?

 let number = 0;
console.log(number++);
console.log(++number);
console.log(number);

Answer:

 0 2 2

The postfix unary operator ++:

Returns the value (this returns 0)

Increments the value (number is now 1)

The prefix unary operator ++:

Increments the value (number is now 2)

Returns the value (this returns 2)

This returns 0 2 2.

57. What will the code below output to the console?

 const obj = { a: 'one', b: 'two', a: 'three' };
console.log(obj);

Answer:

 { a: "three", b: "two" }

If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value.

58. What will the code below output to the console?

 class Pet {
 constructor() {
   console.log("I am a dog.");
 }
}

class Poodle extends Pet {
 constructor() {
   console.log("I am furry.");
   super();
 }
}

Answer:

 I am dog. I am a furry.

We create the variable pet which is an instance of the Poodle class. When we instantiate this instance, the constructor on Poodle gets called. First, "I am furry." gets logged, after which we call super(). super() calls the constructor of the parent class, Pet. The constructor in Pet gets called, and logs "I am a dog.".

59. What will the code below output to the console?

 let randomValue = { name: "Jim" }
randomValue = 23

if (!typeof randomValue === "string") {
console.log("It is not a string!")
} else {
console.log("Yay it is a string!")
}

Answer:

 Yay it is a string!

The condition within the if statement checks whether the value of !typeof randomValue is equal to "string". The ! operator converts the value to a boolean value. If the value is truthy, the returned value will be false, if the value is falsy, the returned value will be true. In this case, the returned value of typeof randomValue is the truthy value "number", meaning that the value of !typeof randomValue is the boolean value false.


!typeof randomValue === "string" always returns false, since we're actually checking false === "string". Since the condition returned false, the code block of the else statement gets run, and "Yay it is a string!" gets logged.

60. What will the code below output to the console?

 let count = 0;
const nums = [0, 1, 2, 3];

nums.forEach(num => {
if (num) count += 1
})

console.log(count)

Answer:;

 3

The if condition within the forEach loop checks whether the value of num is truthy or falsy. Since the first number in the nums array is 0, a falsy value, the if statement's code block won't be executed. count only gets incremented for the other 3 numbers in the nums array, 1, 2 and 3. Since count gets incremented by 1 3 times, the value of count is 3.;;

You can overcome limitations with JavaScript interview questions and answers.

Effective and well-planned interviews should focus on creating a positive experience for both the interviewer and the candidate. These questions and answers will be a great starting point and can properly assess one’s JavaScript knowledge. To delve further into a candidate’s ability you can also incorporate real-world problems into your interview using the examples above.

New Call-to-action

 javascript

Originally published Jun 21, 2022 7:00:00 AM, updated June 21 2022

Topics:

Javascript