Home/Blog/Acing the JavaScript Interview: top questions explained

Acing the JavaScript Interview: top questions explained

Apr 07, 2020 - 21 min read
Amanda Fawcett

JavaScript interviews are not the easiest, and many candidates spent countless hours grinding through scattered coding questions to build confidence. While lots of practice makes all the difference, it also matters how you practice. Having a structured plan will help you master all the fundamental and advanced concepts that interviewers expect.

To get you familiar with the interview prep process and the questions you are expected to know, we’ve compiled an organized list of the need-to-know concepts alongside practical coding solutions.

Today, we will cover:

How to prepare for JavaScript interviews

Coding interviews are notoriously rigorous, and many candidates feel stumped on how to prepare. The hard truth is that there is no silver bullet for acing your JavaScript interview; it all comes down to how much and how well you prepare. Educative is well versed in Coding Interview prep, so we want to walk you through this tried and tested strategy for preparation. Let’s jump in.

Step 1: Know what you need to study

You already know what programming language you will be using, so now you need to research what aspects of that language will be tested. There are three facets to this step:

Know what level you’re interviewing for. It’s unlikely that a Junior Dev position will be expected to know a lot about concurrency. It’s probably expected that a senior dev role will test your system design capabilities. Knowing ahead of time what level you are interviewing at will best prepare you to focus on the important stuff. We all know that these levels can be arbitrary, but being aware of how the company organizes will empower you.

Know what skills are tested. JavaScript is a vast language with multiple versions and a seemingly unlimited number of capabilities. But not all of these will be tested in an interview. It’s also important to understand what technical skills are even included in an interview in general. As you may know, for example, data structures and algorithms come up frequently in interviews, whereas basic language questions are less common.

Know what the organization expects. Some companies will expect different skills than others. Some companies focus on certain JavaScript tools more than others. You need to know what is expected of you from the organization. You can do this research on their company sites, job descriptions, or resources like CodingInterview.com

Cater your preparation to the organization, and you’ll save time and energy.

Step 2: Make a plan

Many people miss this step and end up preparing in a scattered way. Making a plan early on ensures that you cover everything you need to, and it keeps you more motivated. In general, you will need three months to prepare for a coding interview.

There’s a lot to cover, and you don’t want to cram anything last minute. Set aside enough time to do so, and make a plan at the beginning of that period.

We’ve put together a beloved three-month, definitive interview prep roadmap that you can use to make your plan. This roadmap begins with brushing up on the basics, then moves to data structures and algorithms before diving into more complex concepts.

It’s important not to skip the initial refresher or practice. Many people fail to review basic JavaScript principles and end up stumped when it comes to the interview. Build from the basics to the complex stuff, and your learning will be more focused and natural.

Step 3: Don’t forget the behavioral interview

A coding interview will be accompanied by a behavioral interview. This is where the interviewers get to know you as a person and see if your values fit to their organization. These interviews are very important for making employment decisions. Many candidates forget to prepare for behavioral interviews and focus solely on technical skills.

This is a big mistake.

While behavioral interviewing takes less time to prepare, it is still vital to your success and should be accounted for in your plans.

Now that you have a sense of how to prepare for your interviews, let’s dive into the most important JavaScript questions you can expect in an interview.

Questions about JavaScript Language Basics


A question about hoisting may be asked at a senior or junior level. To test your understanding of hoisting in JavaScript, you may be asked a question like this:

What will be the output of the following code?

function Add(){
var answer = 2

In JavaScript, we can declare a variable after it has been used because variable declarations that use var are hoisted to the top of their functional scope at compile time. This means that a variable can be initialized before it is declared. Let’s look at another example.

Note: Only the declarations get hoisted to the top, not the initializations.

var temp = "hi"
function display(){
var temp
temp = "bye"

Here, var temp = ‘bye’ is a function scoped variable. Its declaration var temp is hoisted to the top of the display( ) function at compile time. Since the value bye is after line 4, the output is undefined.

Check parentheses

Checking for balanced parentheses is a common question asked during JavaScript interviews. You may be asked a question like this:

Write a Parentheses Checker function to determine if the input string’s opening and closing brackets are properly nested.

function balancedParentheses(str) {
let stack = [];
let map = {
'(': ')',
'[': ']',
'{': '}'
for (let i = 0; i < str.length; i++) {
// If character is an opening brace add it to a stack
if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {
//if closing brace, pop from stack
else {
let lastEle = stack.pop();
//Return false if the element popped doesn’t match the corresponding closing brace in the map
if (str[i] !== map[lastEle]) {return false};
//if stack not empty at end, return false
if (stack.length !== 0) {return false};
return true;
console.log(balancedParentheses("{[]()}" ));

The solution to this problem is simpler than it looks. First, we declare a stack at line 2, which holds all the opening parentheses. Then, we declare an object map at lines 3-6. This holds the three types of opening parentheses and their closing parentheses.

We then traverse the string expression passed into the function at line 9. If the current character is open, we push it to the stack. If it is a closing bracket, we pop it from the stack. If that character does not match the starting bracket, we tell the program to return false. When we reach the end, any remaining open brackets in the stack will return false.

Array Destructuring

A common challenge in a JavaScript interview asks you to remove the first two elements of an array using array destructuring. Let’s look at the solution.

function removeFirstTwo(list) {
const [, , ...arr] = list;
return arr;
var arrLiteral = [8,9,10,11,12]
console.log("arr contains: " + removeFirstTwo(arrLiteral))

Destructing an array uses a similar syntax as an array literal. On the left of the equation, we define which values we want to retrieve from the right hand side.

const [value1, value2] = arrLiteral

Let’s take a look at how that is stored.

var arrLiteral = [8,9,10,11,12]
const [value1, value2] = arrLiteral
console.log("value1 is: " + value1)
console.log("value2 is: " + value2)

value1 stores the value in arrLiteral, 8, and value2 stores its corresponding value in arrLiteral, 9. We can skip the first two values using a , comma operator. Thus, value1 and value2 store the next two values, 10 and 11.

We can then use the rest parameter arr to collect the remaining values into an array. We return arr at the end. Take a look here.

function removeFirstTwo(list) {
 const [, , ...arr] = list; 
 return arr; // line 3 of original code

Destructure undefined

This common challenge asks you to destructure undefined in JavaScript. Let’s say you input in the point variable, and we want the output values of name and age properties. Take a look.

function pointValues(point){
const {name:n,age:a} = {...point}
pointValues({name:"jerry", age:2})

If it is an object, the code displays name and age values of point, which will give an error of undefined. We need to spread the point into an object before we can destructure it.

const {name:n,age:a} = {...point} 

We do that using {...point}, which creates a new object using the properties of point. Now, the new object will contain all the same values as a kind of copy. The values undefined and null are ignored. When undefined is spread, no value is stored in the new object, so no error is thrown. Thus, we see undefined when we access name and age.

Other questions

There are many other JavaScript interview questions to test your knowledge of language basics. Some of those include:

  • Define a function, createPhoneNumber, that accepts an array of 10 integers (from 0-9) and returns a string of those numbers in the form of a phone number.
  • Given an array of coins, write a function to compute the number of ways you can make that amount using those coins.
  • How does the arrow function differ from other functions?
  • What’s the notable difference between the Function.call and Function.apply methods?
  • Is it possible to run an asynchronous code in JavaScript?
  • You’re given a function returnNthCat that takes a variable n and has an object state defined in it. Return the name value of the nth cat object.

Questions about Type coercion

instance of

A common question for JavaScript interviews asks about the instanceof operator. You may get a problem like this:

What will be the output of the code below?

var names = ["Tom","Anna",2,true]
console.log(names instanceof String)
console.log(names instanceof Number)
console.log(names instanceof Object)
console.log(names instanceof Array)

The instanceof operator checks if an operand is an instance of the object passed on the right or an instance of any of its ancestors. The answer false false true true is correct because we are using an array, names that contains the values of string, number, and boolean types.

names is not an instance of the string or number, but rather an array that is the instance of Array. In JavaScript, Array is an object, so names is also an instance of Object.

Array or not?

A common problem tested looks like this:

Implement a function check that takes an object and determines if it is an array or not. It should return either true or false.

Take a look at the answer:

function check(obj) {
if (Object.prototype.toString.call(obj) === "[object Array]") {
return true;
} else {
return false;
console.log(check([1, 2, 3, 4]));

To check if an object is an array, we must use the Object.prototype.toString method, which returns a string in the form of [object Type]. If we call it on 123, we return the string [object Number. If we call it on {}, we will return [object Object]. If we call it on an array, we should return [object Array].

On line 2, see how we compare the returned string from Object.prototype.toString with [object Array]. If they match, we return true, otherwise, false.

Instance of array?

This question, which tests your knowledge of instanceof, is a bit trickier. Take a look at the code below:

function check(){
var tempFunc = function () {}
return new tempFunc instanceof Array;

The check function contains the definition of tempFunc, and on line 4, we are checking if an instance of tempFunc is an instance of Array. Your task is to write code on line 3 so that the statement returns true. Let’s break down the solution.

function check(){
var tempFunc = function () {}
tempFunc.prototype = Array.prototype
return new tempFunc instanceof Array;

We need to modify the code so that the new object becomes an instance of the array. We need to make a modification so that Array.prototype is present in the prototype chain of tempFunc.

tempFunc.prototype = Array.prototype //line 3

Now, we set the tempFunc.prototype as equal to Array.prototype. It should now return true.

Other questions

There are many other JavaScript interview questions to test your knowledge of type coercion. basics. Some of those include:

  • What will the following code display?
console.log(Object.prototype.toString.call(new (function Custom(){})));

  • What is the purpose of the typeof operator?
  • Validate arguments skills using typeof operator in JavaScript
  • Validate the date skills using prototype.toString and arrow functions
  • And more

Questions about OOP in JavaScript


This question challenges your ability to implement object methods using the isPrototypeOf function in JavaScript. Say you’re given the following code:

function isPrototype(){
var obj1 = {x: 1};
var obj2;

You would be asked to write code for obj2 so that the statement returns true on line 5. We need obj1 to become part of obj2’s prototype chain. We can do this using the Object.create function, which creates an object to store in variable obj2.

Object.create takes it as a parameter and returns an object with a prototype property that points to obj1. This makes obj1 the prototype chain, so Object.getPrototypeOf(obj2) will return as obj1.

function isPrototype(){
var obj1 = {x: 1};
var obj2 = Object.create(obj1)

ES6 classes

ES6 skills are important in JavaScript interviews, as they show you are up to date with your JavaScript skills. Say you’re given the following code:

function Cat (name) {
this.name = name
Cat.meow = function () {
console.log(this.name + ' says meow')
let catty = new Cat('catty')

You would be asked to modify the code to resolve its error, but you can only use ES6 classes. The error in this code is because meow is not defined on the prototype Cat, so it is not inherited by the object catty. We need to redefine it as a prototype but replacing the keyword function with class.

We can then define a constructor inside the class to take name as an argument. Once we do that, we can define a new method, meow, inside the new class, so meow is part of Cat. It will then inherit all its methods, so catty.meow() will not result in an error.

class Cat {
constructor (name) {
this.name = name
meow () {
console.log(this.name + ' says meow')
let catty = new Cat('catty')

Prototypal Inheritance

Since JavaScript is a prototype-based inheritance language, you can expect questions like these to test your skills. Say you are given the following code:

function Human(name, age) {
this.name = name;
this.age = age;
function Man(name) {
function check(){
var obj = new Man("Tommy Tan");
console.log(obj instanceof Human)

You would be asked to implement inheritance between the class Human and Man. The code should compile successfully. Let’s look at the solution.

function Human(name, age) {
this.name = name;
this.age = age;
function Man(name,age) {
Human.call(this, name, age);
Man.prototype = Object.create(Human.prototype);
Man.prototype.constructor = Man;
function check(){
var obj = new Man("Tommy Tan",20);
console.log(obj instanceof Human)

Human is the parent, which the child Man inherits. In order for Man to inherit its properties, we must call the constructor of the parent in Man’s constructor function. This will initialize members desired from the parent, name and age.

This process enables obj to access name property, so you will see name instead of undefined. Line 10 creates a prototype chain, which means that any Man will have Human as its prototype. Now, obj instanceof Human will return true.

Once we set Man.prototype to Human, its constructor pointer will point to it. We correct this by setting the constructor property to point to Man on line 11, but this is optional to preserve the constructor property.

Other questions

There are many other JavaScript interview questions to test your knowledge of Object Oriented programming JavaScript. Some of those include:

  • Questions related to this keyword
  • Questions related to the super keyword
  • Differences between ES5 and ES6
  • Creating an object instance from a class
  • Which of the following are native JavaScript objects?
  • How do objects work in JavaScript?
  • How do you create an object literal?
  • And more

If you want to learn more about Object Oriented programming in JavaScript, check out this guide for an introduction or refresher.

Questions about Functional Programming

Pure function

Pure functions are an important JavaScript skill. You could expect questions like these that test for your problem solving skills.

The following code has an impure function addAndPrint. Modify it into a pure function.

const addAndPrint = (a, b) => {
const sum = a+b;
console.log(`The sum is ${sum}`);
return sum;
const ans = addAndPrint(4,5)

First, you must figure out why the function is impure. The addAndPrint appears to have no negative side effects on an external state. However, the console.log statement has a side effect that violates the rule that a result should not cause a side effect, such as a mutation of mutable objects. We must convert it to a pure function by removing console.log.

Remember that any work a function performs that isn’t directly related to calculating a final output is a side effect!

const addAndPrint = (a, b) => {
const sum = a+b;
return sum;
const ans = addAndPrint(4,5)
console.log("The sum is " + ans)

Shallow copying

You can expect questions about shallow copying in JavaScript. Say you’re given the following code and asked for its output.

const girl = {
name: 'Anna',
info: { age: 20, number: 123 }
const newGirl = { ...girl };
newGirl.info.age = 30;
console.log(girl.info.age, newGirl.info.age);

The correct output is 30 30. Why? The object girl has properties name and info. We copy the properties of that object into newGirl using the spread operator, which creates a shallow copy. Both share a reference because objects are passed through reference in JavaScript.

This means that when you assign an object to a variable, it is linked to that object’s identity. When we assign girl to newGirl, newGirl points to the same object as girl, so their properties will both change if altered.

Higher order functions

Questions about higher order functions are important for standing out in your JavaScript interview. You could expect a question like this.

Study the code below. Is func1 a higher order function?

const func1 = function(num){
return function(){
if(typeof num == 'NaN'){
return "Not a number"
return typeof(num)

Higher-order functions are those that accept functions as parameters or return a function as their output. When we look at the code, we can see that func1 does not take a function as a parameter. If we look harder at line 2, however, we see that it does return a function as its output. Therefore, yes, it is a higher order function.

Other questions

There are many other questions in a JavaScript interview that test your knowledge of functional programming. Some of those questions and concepts may be:

  • Turn an impure function into a pure function that returns a new object containing new properties
  • Create a function maxCookies that returns the maximum number of whole cookies that can be cooked from a recipe
  • Implement the reduce function in JavaScript
  • Basics of currying functions
  • Implement the basics of partial functions
  • And more

Questions about DOM and Web Browser

What is the DOM

To test your knowledge of JavaScript and DOM skills, you may be asked questions like,

What is the difference between feature detection and feature inference?

We can use feature detection and feature inference to determine if a web technology exists in the browser. Feature detection figures out if a feature exists in a specific browser. Feature inference assumes that if a feature is available in one browser, it is available in others. This question may be asked in a junior-level interview.

You could also be asked about attributes and properties. An attribute is written in the HTML document, in which the HTML tags may have attributes. When that document is covered to a DOM object model, the attributes are converted to properties.

Hide and Show

You will also be expected to demonstrate your ability to implement DOM related functions, such as to hide and show text. For example, you would be asked to implement text hiding functionality, where clicking on the button hides the text Hello World!. Take a look at the solution.

function hideShow() {
var ele = document.getElementById("hideDiv");
if (ele.style.display === "none") {
ele.style.display = "block";
} else {
ele.style.display = "none";

We create a button that executes the hideShow function, and a div with the text. We use getElementById to access that div element. On line 3, we check if the style.display property is none (aka. hidden). If true, we show the element by setting the display property to block. If false, we hide it by setting the display value to none.

Other questions

There are many other JavaScript interview questions to test your knowledge of DOM and web browser skills in JavaScript. Some of those include:

  • DOM related functions to create getElementByAttribute
  • Implement the query selector to add a class
  • Destroy and create new buttons
  • Implement DOM related function to find if an element is a child
  • And more

Questions about data structures and algorithms

Data structures and algorithms are a key part of all coding interviews. Interviewers will expect you to demonstrate mastery over these concepts and apply them to real-world challenges. Let’s go over a few of the most popular JavaScript data structures that you need to know.


Problem statement: Implement a function removeEven(arr), which takes an array arr in its input and removes all the even elements from a given array.

Input: An array of random integers


Output: an array containing only odd integers

function removeEven(arr) {
var odds = []
for (let number of arr) {
if (number % 2 != 0) // Check if the item in the list is NOT even ('%' is the modulus symbol!)
odds.push(number) //If it isn't even append it to the empty list
return odds // Return the new list
console.log(removeEven([3, 2, 41, 3, 34]))

This approach starts with the first element of the array. If that current element is not even, it pushes this element into a new array. If it is even, it will move to the next element, repeating until it reaches the end of the array. In regards to time complexity, since the entire array has to be iterated over, this solution is in O(n)O(n).


Problem statement: Implement the isBalanced() function to take a string containing only curly {}, square [], and round () parentheses. The function should tell us if all the parentheses in the string are balanced. This means that every opening parenthesis will have a closing one. For example, {[]} is balanced, but {[}] is not.

Input: A string consisting solely of (, ), {, }, [ and ]

exp = "{[({})]}"

Output: Returns False if the expression doesn’t have balanced parentheses. If it does, the function returns True.


To solve this problem, we can simply use a stack of characters. Look below at the code to see how it works.

"use strict";
module.exports = class Stack {
constructor() {
this.items = [];
this.top = null;
getTop() {
if (this.items.length == 0)
return null;
return this.top;
isEmpty() {
return this.items.length == 0;
size() {
return this.items.length;
push(element) {
this.top = element;
pop() {
if (this.items.length != 0) {
if (this.items.length == 1) {
this.top = null;
return this.items.pop();
} else {
this.top = this.items[this.items.length - 2];
return this.items.pop();
} else
return null;

This process will iterate over the string one character at a time. We can determine that the string is unbalanced based on two factors:

  1. The stack is empty.
  2. The top element in the stack is not the right type.

If either of these conditions is true, we return False. If the parenthesis is an opening parenthesis, it is pushed into the stack. If by the end all are balanced, the stack will be empty. If it is not empty, we return False. Since we traverse the string exp only once, the time complexity is O(n).


Problem statement: Implement a function findBin(n), which will generate binary numbers from 1 to n in the form of a string using a queue.

Input: A positive integer n

n = 3

Output: Returns binary numbers in the form of strings from 1 up to n

result = ["1","10","11"]

The easiest way to solve this problem is using a queue to generate new numbers from previous numbers. Let’s break that down.

"use strict";
const Queue = require('./Queue.js');
function findBin(n) {
let result = [];
let myQueue = new Queue();
var s1, s2;
for (var i = 0; i < n; i++) {
s1 = result[i] + "0";
s2 = result[i] + "1";
return result;

The key is to generate consecutive binary numbers by appending 0 and 1 to previous binary numbers. To clarify,

  • 10 and 11 can be generated if 0 and 1 are appended to 1.
  • 100 and 101 are generated if 0 and 1 are appended to 10.

Once we generate a binary number, it is then enqueued to a queue so that new binary numbers can be generated if we append 0 and 1 when that number will be enqueued. Since a queue follows the First-In First-Out property, the enqueued binary numbers are dequeued so that the resulting array is mathematically correct.

Look at the code above. On line 7, 1 is enqueued. To generate the sequence of binary numbers, a number is dequeued and stored in the array result. On lines 11-12, we append 0 and 1 to produce the next numbers. Those new numbers are also enqueued at lines 14-15. The queue will take integer values, so it converts the string to an integer as it is enqueued.

The time complexity of this solution is in O(n)O(n) since constant-time operations are executed for n times.

Linked List

Problem statement: Write the reverse function to take a singly linked list and reverse it in place.

Input: a singly linked list

LinkedList = 0->1->2->3-4

Output: a reverse linked list

LinkedList = 4->3->2->1->0

The easiest way to solve this problem is by using iterative pointer manipulation. Let’s take a look.

"use strict";
module.exports = class Node {
constructor(data) {
this.data = data;
this.nextElement = null;

We use a loop to iterate through the input list. For a current node, its link with the previous node is reversed. then, next stores the next node in the list. Let’s break that down by line.

  • Line 22- Store the current node’s nextElement in next
  • Line 23 - Set current node’s nextElement to previous
  • Line 24 - Make the current node the new previous for the next iteration
  • Line 25 - Use next to go to the next node
  • Line 29 - We reset the head pointer to point at the last node

Since the list is traversed only once, the algorithm runs in O(n).


Problem statement: Use the findMin(root) function to find the minimum value in a Binary Search Tree.

Input: a root node for a binary search tree

bst = {
    6 -> 4,9
    4 -> 2,5
    9 -> 8,12
    12 -> 10,14
where parent -> leftChild,rightChild

Output: the smallest integer value from that binary search tree


Let’s look at an easy solution for this problem

This solution begins by checking if the root is null. It returns null if so. It then moves to the left subtree and continues with each node’s left child until the left-most child is reached.

"use strict";
module.exports = class Node {
constructor(value) {
this.val = value;
this.leftChild = null;
this.rightChild = null;

Miscellaneous questions

You can also expect to see questions that deal with security, even handling, and asynchronous callbacks in JavaScript. Let’s look at a few common concepts you will be expected to know.

Event Handling

  • Event loops, event queues, and call stack in JavaScript
  • What is the difference between call stack and task queue?
  • Event bubbling and console outputs
  • Event capturing and console outputs
  • Which methods will prevent event bubbling?
  • And more

Asynchronous callbacks

  • Async and await principles Modify code with a func is not a function error
  • Implement the checkName function to implement error checks
  • Modify code with a Cannot read property ‘text’ of undefined error
  • Basics of promises, chaining, .then and .catch statements print the numbers 0-9 in a sequential manner, so that each number is printed after a random waiting time.
  • And more


  • What is the same origin policy?
  • Understanding/implementing strict keyword in JavaScript
  • Modify code to throw errors for specific changes
  • And more

Next steps

JavaScript interview prep takes a lot of time and hard work, but it’s worth it in the end! Javascript continues to be one of the most popular and high paying programming languages.

To help you prepare for interviews, Educative has created the unique course Grokking Coding Interview Patterns in JavaScript. Available in multiple languages, this course takes you through 100+ real-world questions like these. After each project, you’ll better understand what techniques you just applied.

This is coding interview prep reimagined, with your needs in mind.

Happy learning!

Continue reading about JavaScript

WRITTEN BYAmanda Fawcett

Join a community of more than 1.6 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.