Skip to content
Hoodie for your thoughts: take the Developer Skills Survey for a chance to win free merch Start survey
69% of tech leaders are preparing their teams for GenAI. Uncover more insights in the AI Skills Report. Read now
Adapt your hiring strategy for an AI-powered future. Uncover more insights in our latest whitepaper. Read now
Programming Languages

7 JavaScript Interview Questions Every Developer Should Know

Written By April Bohnert | May 30, 2023

An AI-generated image with colorful shapes and connections

JavaScript has emerged as the cornerstone of modern web development, enabling dynamic and interactive experiences that shape the digital landscape. As a result of its widespread use, it also happens to be one of the world’s most ​​in-demand programming languages

As a JavaScript developer, excelling in technical interviews is paramount for showcasing your expertise and securing coveted positions in the industry, and a great way to prepare is to put your skills to the test.

In this blog post, we’ll explore seven intermediate-to-advanced JavaScript interview questions that will push the boundaries of your problem-solving skills, challenge your understanding of key concepts, and demonstrate your ability to navigate complex scenarios. Whether you are a seasoned JavaScript developer seeking to refresh your interview readiness or a hiring manager looking to identify top talent, this guide will equip you with invaluable insights and practical examples.

Inside a JavaScript Interview

JavaScript, often referred to as the “language of the web,” is a versatile programming language that plays a vital role in modern web development. It is primarily used to create interactive and dynamic elements on websites, enabling a rich user experience. 

When it comes to JavaScript interviews, they serve as a critical evaluation of a candidate’s JavaScript proficiency, problem-solving skills, and understanding of key concepts. A JavaScript interview can take various forms, depending on the company and position. However, it typically involves one or more of the following assessment formats:

  • Technical screenings
  • Coding challenges
  • Whiteboard exercises
  • Take-home assignments
  • Pair programming sessions
  • Behavioral interviews

These components are designed to assess different aspects of a candidate’s capabilities and provide a comprehensive evaluation of their JavaScript knowledge and expertise.

Roles that require candidates to complete a JavaScript interview span a wide range of technical positions. Web developers, back-end developers, front-end developers, and software engineers often encounter JavaScript interview questions as part of the hiring process. Additionally, positions in mobile app development, UI/UX design, and even emerging technologies like serverless computing may involve JavaScript assessments to gauge a candidate’s ability to work with its frameworks and libraries.

#1. Reverse Words in a Sentence

This question focuses on reversing the order of words in a given sentence, demonstrating a developer’s proficiency with string manipulation, loops, conditionals, and other programming constructs.

Task: Write a JavaScript function called reverseWords that takes a sentence as input and returns the sentence with the order of words reversed.

Input Format: The input will be a string representing the sentence.

Constraints:

  • The sentence will contain only alphanumeric characters and spaces.
  • There will be no leading or trailing spaces.
  • The sentence will have at least one word.

Output Format: The output will be a string representing the sentence with the words reversed.

Sample Input: JavaScript is awesome

Sample Output: awesome is JavaScript

Sample Code:

function reverseWords(sentence) {

    const words = sentence.split(” “);

    const reversedWords = words.reverse();

    const reversedSentence = reversedWords.join(” “);

    return reversedSentence;

}

Explanation:

  • The reverseWords function starts by splitting the sentence into individual words using the split(” “) method. This creates an array of words.
  • Next, the function uses the reverse() method to reverse the order of the words in the array.
  • The reversed words are then joined back together using the join(” “) method, where the space character ” “ is used as the separator.
  • Finally, the reversed sentence is returned.

#2. Find the Nth Largest Element in an Array

This question delves into array manipulation and algorithmic problem solving, showcasing a developer’s ability to work with arrays and efficiently find the nth largest element.

Task: Write a JavaScript function called findNthLargest that takes an array of numbers and an integer n as input, and returns the nth largest element from the array.

Input Format

  • The input will be an array of numbers.
  • An additional integer n will be provided.

Constraints

  • The array will contain at least n elements.
  • The array may have duplicates.
  • The values in the array can be both positive and negative.

Output Format: The output will be the nth largest element as a number.

Sample Input:

const numbers = [10, 5, 3, 8, 2];

const n = 3;

Sample Output: 5

Sample Code:

function findNthLargest(numbers, n) {

    numbers.sort((a, b) => b – a);

    return numbers[n – 1];

}

Explanation:

The findNthLargest function starts by sorting the numbers array in descending order using the sort() method with a custom comparison function (a, b) => b – a. This places the largest numbers at the beginning of the array.

Then, the function returns the element at index n – 1 since arrays are zero-indexed. In our example, we want to find the 3rd largest element, so we access numbers[2], which is 5.

#3. Implementing a Linked List

This question focuses on data structures and their implementation in JavaScript, specifically the Linked List. Demonstrating proficiency in data structures showcases a developer’s ability to design efficient and scalable solutions.

Task: Implement a Linked List in JavaScript with the following operations:

  • insert(value): Inserts a new node with the given value at the end of the list.
  • delete(value): Removes the first occurrence of the node with the given value from the list.
  • search(value): Returns true if a node with the given value exists in the list, false otherwise.

Sample Code:

class Node {

    constructor(value) {

        this.value = value;

        this.next = null;

    }

}

class LinkedList {

    constructor() {

        this.head = null;

    }

    insert(value) {

        const newNode = new Node(value);

 

        if (!this.head) {

            this.head = newNode;

        } else {

            let current = this.head;

            while (current.next) {

                current = current.next;

            }

            current.next = newNode;

        }

    }

    delete(value) {

        if (!this.head) {

            return;

        }

        if (this.head.value === value) {

            this.head = this.head.next;

            return;

        }

        let current = this.head;

        let previous = null;

        while (current && current.value !== value) {

            previous = current;

            current = current.next;

        }

        if (!current) {

            return;

        }

        previous.next = current.next;

    }

    search(value) {

        let current = this.head;

        while (current) {

            if (current.value === value) {

                return true;

            }

            current = current.next;

        }

        return false;

    }

}

// Usage example:

const linkedList = new LinkedList();

linkedList.insert(5);

linkedList.insert(10);

linkedList.insert(15);

linkedList.delete(10);

console.log(linkedList.search(5)); // Output: true

console.log(linkedList.search(10)); // Output: false

 

Explanation:

The code snippet above demonstrates the implementation of a Linked List in JavaScript. 

The Node class represents a single node in the Linked List, containing a value property to store the node’s value and a next property to reference the next node in the list.

The LinkedList class represents the Linked List itself. It has a head property that initially points to null. The insert method inserts a new node with the given value at the end of the list by traversing to the last node and appending the new node. The delete method removes the first occurrence of a node with the given value from the list by updating the next references of the surrounding nodes. The search method traverses the list to check if a node with the given value exists.

In the usage example, we create a new Linked List, insert nodes with values 5, 10, and 15, delete the node with value 10, and then perform search operations to check for the existence of nodes with values 5 and 10.

#4. Implementing a Class Hierarchy with Inheritance

This question delves into object-oriented programming (OOP) concepts in JavaScript, specifically class hierarchies and inheritance. Demonstrating proficiency in OOP showcases a developer’s ability to design modular and reusable code.

Task: Implement a class hierarchy in JavaScript with inheritance, following the given specifications:

  • Create a base class called Shape with the following properties and methods:
    • name: a string representing the name of the shape.
    • area(): a method that calculates and returns the area of the shape (to be implemented by subclasses).
  • Create a subclass called Rectangle that extends the Shape class. It should have the following additional properties and methods:
    • width: a number representing the width of the rectangle.
    • height: a number representing the height of the rectangle.
    • Implement the area() method to calculate and return the area of the rectangle.
  • Create another subclass called Circle that extends the Shape class. It should have the following additional properties and methods:
    • radius: a number representing the radius of the circle.
    • Implement the area() method to calculate and return the area of the circle.

Sample Code

class Shape {

    constructor(name) {

        this.name = name;

    }

    area() {

        // To be implemented by subclasses

    }

}

class Rectangle extends Shape {

    constructor(name, width, height) {

        super(name);

        this.width = width;

        this.height = height;

    }

    area() {

        return this.width * this.height;

    }

}

class Circle extends Shape {

    constructor(name, radius) {

        super(name);

        this.radius = radius;

    }

    area() {

        return Math.PI * Math.pow(this.radius, 2);

    }

}

// Usage example:

const rectangle = new Rectangle(“Rectangle”, 5, 3);

console.log(rectangle.area()); // Output: 15

const circle = new Circle(“Circle”, 4);

console.log(circle.area()); // Output: 50.26548245743669

Explanation:

The code snippet above demonstrates the implementation of a class hierarchy in JavaScript using inheritance.

The Shape class serves as the base class, providing a common name property for all shapes and a placeholder area() method that is meant to be implemented by subclasses.

The Rectangle class extends the Shape class using the extends keyword. It introduces additional properties width and height and overrides the area() method to calculate and return the area of a rectangle based on its width and height.

The Circle class also extends the Shape class and adds the radius property. The area() method is implemented to calculate and return the area of a circle based on its radius, using the formula π * r^2.

In the usage example, we create instances of the Rectangle and Circle classes, passing the necessary parameters. We then call the area() method on each instance to calculate and display the area of the respective shape.

#5. Finding the Longest Substring Without Repeating Characters

This question focuses on problem-solving skills and string manipulation. It challenges developers to find an efficient algorithm for finding the longest substring in a given string without repeating characters.

Task: Write a JavaScript function called findLongestSubstring that takes a string as input and returns the length of the longest substring without repeating characters.

Input Format: The input will be a string.

Constraints:

  • The string may contain uppercase and lowercase letters, digits, symbols, or spaces.
  • The string can have both single and multiple words.

Output Format: The output will be an integer representing the length of the longest substring without repeating characters.

Sample Input: abcabcbb

Sample Output: 3

Sample Code:

function findLongestSubstring(str) {

    let maxLength = 0;

    let start = 0;

    const charMap = {};

    for (let i = 0; i < str.length; i++) {

        const currentChar = str[i];

        if (charMap[currentChar] >= start) {

            start = charMap[currentChar] + 1;

        }

        charMap[currentChar] = i;

        maxLength = Math.max(maxLength, i – start + 1);

    }

    return maxLength;

Explanation:

The findLongestSubstring function utilizes the sliding window technique to efficiently find the length of the longest substring without repeating characters.

The function initializes maxLength to 0, start to 0, and an empty charMap object to keep track of the most recent occurrence of each character in the string.

The function then iterates through the string using a for loop. For each character, it checks if the character has been previously encountered within the current substring (i.e., its index is greater than or equal to start). If so, it updates the start index to the next position after the previous occurrence of the character.

The function updates the charMap with the current character’s index. It also calculates the length of the current substring by subtracting start from the current index and adding 1. The maximum length is updated using Math.max() to keep track of the longest substring found so far.

Finally, the function returns the maxLength, representing the length of the longest substring without repeating characters.

#6. Sum of Two Numbers in an Array

This question challenges your problem-solving skills and array manipulation techniques. It requires finding two numbers in an array that add up to a given target sum.

Task: Write a JavaScript function called findSumOfTwo that takes an array of numbers and a target sum as input and returns an array containing the two numbers that add up to the target sum. If no such pair is found, return an empty array.

Input Format: The input will be an array of numbers and a target sum.

Constraints:

  • The array may contain positive and negative integers.
  • The array may have duplicates.
  • The array can be empty.

Output Format: The output will be an array containing the two numbers that add up to the target sum, or an empty array if no such pair is found.

Sample Input:

const arr = [2, 4, 7, 11, 15];

const target = 9;

Sample Output: [2, 7]

Sample Code:

function findSumOfTwo(arr, target) {

    const numMap = {};

    for (let i = 0; i < arr.length; i++) {

        const num = arr[i];

        const complement = target – num;

        if (numMap[complement] !== undefined) {

            return [complement, num];

        }

        numMap[num] = i;

    }

    return [];

}

Explanation:

The findSumOfTwo function utilizes a hash map to efficiently find the pair of numbers that add up to the target sum.

The function initializes an empty numMap object to store the numbers and their corresponding indices encountered during the iteration.

It then iterates through the array using a for loop. For each number num, it calculates the complement by subtracting num from the target

The function checks if the complement exists as a key in the numMap object. If it does, it means that a pair of numbers that adds up to the target sum has been found. The function returns an array containing the complement and num.

If no such pair is found during the iteration, the function returns an empty array [].

#7. Working with Asynchronous JavaScript and Callbacks

This question dives into asynchronous programming in JavaScript and challenges developers to work with callbacks to handle asynchronous operations.

Task: Write a JavaScript function called fetchData that simulates an asynchronous API call and takes a callback function as an argument. The callback function should be invoked with the retrieved data as its parameter.

Input Format: The input will be a callback function.

Output Format: The output will be the retrieved data passed to the callback function.

Sample Input:

function handleData(data) {

    console.log(“Received data:”, data);

}

fetchData(handleData);

Sample Output:

Received data: { name: ‘John’, age: 28, city: ‘New York’ }

Sample Code:

function fetchData(callback) {

    // Simulating an asynchronous API call with a setTimeout

    setTimeout(() => {

        const data = { name: ‘John’, age: 28, city: ‘New York’ };

        callback(data);

    }, 2000);

}

Explanation:

The fetchData function simulates an asynchronous API call using setTimeout. In this example, it waits for 2,000 milliseconds (2 seconds) before invoking the callback function with the retrieved data.

In the sample input, the handleData function is defined as the callback function. When fetchData is called, it waits for 2 seconds and then invokes the handleData function, passing the retrieved data as the parameter.

The handleData function in this case simply logs the received data to the console.

Resources to Improve JavaScript Knowledge

This article was written with the help of AI. Can you tell which parts?