DEV Community

Cover image for Acing the JavaScript Interview: top questions explained
Amanda Fawcett for Educative

Posted on • Originally published at educative.io

Acing the JavaScript Interview: top questions explained

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:

Alt Text

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 for 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 sites like Coding Interview. 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.

For five tried and true tips for building your interview prep plan, check out this article.

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. To learn more about behavioral interviewing, check out this article which walks you through the process entirely.

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

Hoisting

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(){
    console.log(answer)
    var answer = 2
};
Add()
Enter fullscreen mode Exit fullscreen mode

Output: undefined

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
  console.log(temp)
  temp = "bye" 
}
display()
Enter fullscreen mode Exit fullscreen mode

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] === '[' ) {
            stack.push(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("{[]()}" ));
console.log(balancedParentheses("{[(])}"));
console.log(balancedParentheses("{[}"));
Enter fullscreen mode Exit fullscreen mode

Output: true false false

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))
Enter fullscreen mode Exit fullscreen mode

Output: arr contains: 10,11,12

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output: value1 is:8 value2 is:9

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
} 
Enter fullscreen mode Exit fullscreen mode

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} 
    console.log(n)
    console.log(a)
}
pointValues({name:"jerry", age:2})
pointValues(undefined)
Enter fullscreen mode Exit fullscreen mode

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} 
Enter fullscreen mode Exit fullscreen mode

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.

If you want to see other common JavaScript language questions or explore the solutions to these questions, check out the course The JavaScript Interview Handbook: 100+ Interview Questions for hands-on practice with all these challenges and more.


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)
Enter fullscreen mode Exit fullscreen mode

Output: false false true true

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(123));
console.log(check("cat"));
console.log(check([1, 2, 3, 4]));
Enter fullscreen mode Exit fullscreen mode

Output: false false true

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; 
}
console.log(check())
Enter fullscreen mode Exit fullscreen mode

Output: false

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; 
}
console.log(check())
Enter fullscreen mode Exit fullscreen mode

Output: true

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
Enter fullscreen mode Exit fullscreen mode

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(){})));

Enter fullscreen mode Exit fullscreen mode
  • 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

isPrototypeOf

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;

  console.log(
    obj1.isPrototypeOf(obj2)  
  ); 

}
isPrototype()
Enter fullscreen mode Exit fullscreen mode

Output: false

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)
  console.log(
    obj1.isPrototypeOf(obj2)       
);
} 
isPrototype()
Enter fullscreen mode Exit fullscreen mode

Output: false

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')
catty.meow()
Enter fullscreen mode Exit fullscreen mode

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') 
catty.meow()
Enter fullscreen mode Exit fullscreen mode

Output: catty says meow

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.name) 
    console.log(obj instanceof Human) 
}
check()
Enter fullscreen mode Exit fullscreen mode

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.name) 
    console.log(obj instanceof Human) 
}
check()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output: The sum is 9

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)
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"
    }else{
      return typeof(num)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Keep the learning going.

Practice for JavaScript interviews without scrubbing through videos or documentation. Educative's text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.
The JavaScript Interview Handbook: 100+ Interview Questions

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

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

If you want to learn more about DOM and web browser skills in JavaScript, check out this guide for an introduction or refresher.


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

Security

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

Alt Text

Resources

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. Make a detailed plan, study hard, and ask questions when they come up. To best prepare you for the studying ahead, we’ve compiled a list of useful resources to aid your interview prep.

Courses

  • The JavaScript Interview Handbook: we’ve compiled a list of 100+ interview questions on need-to-know topics to simplify your interview prep process. This course focuses on the fundamental questions of JavaScript that interviewers expect you to know. Learn through hands-on practice and coding.

  • Data Structures in JavaScript - Visualization and Exercises: want more hands-on practice? This course cuts to the core of data structures problems with simple visuals and quizzes.

  • Master the JavaScript Interview: once you get down your data structures skills, it’s time to refresh your knowledge on everything related to JS interviews. This course has it all.

Articles

Top comments (5)

Collapse
 
campbellgoe profile image
George O. E. Campbell

For the 'Array or not?' section, you can instead use the built-in Array.isArray() method, rather than parsing the output of object.toString().

Collapse
 
amandaeducative profile image
Amanda Fawcett

Thank you for the reminder - should be fixed now!

Collapse
 
tarun_geek profile image
Tarun Nagpal

Looks like a plan.

Thanks for sharing. I will try

Collapse
 
madza profile image
Madza

Nice article. I wish answers would be somewhat hidden (not right below the task), so reader can figure it out himself/herself and then check if he/she was right.

Collapse
 
krlz profile image
krlz

thanks just what i needed