Mastering Your JavaScript Interview: Top Questions and Answers for 2023

Danielle Ellis
Danielle Ellis


Are you ready to shine in your upcoming JavaScript interview? Do you feel confident about the possible questions that will come your way? Or, if you're interviewing potential candidates, do you know what type of questions are best suited for the position at hand?

Senior JavaScript developers performing a coding interviewing with junior JavaScript developer in an office.

Download Now: An Introduction to Java & JavaScript

You've done the hard part and narrowed down your top candidates or are presented with a fantastic chance to interview. Congratulations! No matter which side of the table you're on, being adequately prepped is essential to achieving success in an interview.

To help you prepare for your JavaScript interview, we've put together a comprehensive guide featuring the top interview questions and answers for 2023. In this blog, you'll find practical tips to help you ace your interview and stand out from the competition.

Let's dive in!


Beginner-Level JavaScript Interview Questions and Answers

1. What is JavaScript, and what are its key features?

JavaScript is a programming language used primarily for creating dynamic web content and user interfaces. It is a popular language among web developers due to its ability to enhance the interactivity of web pages.

Some key features of JavaScript include:

  • Object-oriented: This means that it uses objects and classes to organize and structure code, making it more efficient and easier to read.
  • Lightweight: JavaScript is a lightweight language that doesn't require much processing power to run.
  • Versatile: JavaScript can run on both the client side (in a web browser) and the server side (on a web server).
  • Interactivity: JavaScript is designed to make web pages more interactive and dynamic.
  • Cross-platform compatibility: JavaScript is compatible with all major web browsers.

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

The main difference between "let" and "const" is that "let" allows the variable to be reassigned, while "const" creates a read-only reference to a value that cannot be reassigned.


let x = 1; const y = 2; x = 3; // valid y = 4; // invalid - will throw an error

3. What is the difference between "==" and "===" in JavaScript?

== (called loose equal) is used to compare two variables regardless of the variable's data type.

=== (called strict equal) is used to compare two variables, but this will check strict type, which means it will check the data type and compare two values.


1 == "1" // true - 1 is converted to a string 1 === "1" // false - they are not the same type of value

4. What is an object in JavaScript?

An object in JavaScript is a collection of properties containing primitive data types, such as strings, numbers, booleans, and functions. An object can also have other objects as its values. Objects are used to model real-world entities and help organize code into reusable components.

They are defined using curly braces "{}" and properties are defined as key-value pairs separated by a colon ":".


const person = { name: "Alex", age: 30, sayHello: function() { console.log("Hello!"); } };

In this example, we define an object called "person" that has three properties: "name", "age", and "sayHello". The "sayHello" property is a method, which is a function that belongs to the object.

5. What is an array in JavaScript?

An array in JavaScript is an ordered list of elements containing any data type, including primitive types such as strings and numbers, objects, and other arrays. Arrays are used to store collections of data and can be iterated over using loops like forEach().

They are defined using square brackets "[]" and elements are separated by commas ",".


const numbers = [1, 2, 3, 4];

In this example, we define an array called "numbers" that contains four elements, which are all numbers.

6. What is a function in JavaScript?

A function in JavaScript is a reusable piece of code that can be used to perform a specific task. Functions are defined using the keyword "function" followed by a name and parentheses "( )". The code inside the parentheses is the body of the function, which contains instructions for how it should behave.


function greet(name) { console.log("Hello, " + name + "!"); }

7. What is an event in JavaScript?

An event is an action or occurrence that happens as a result of user interaction, such as clicking a button, hovering over an element, or pressing a key on the keyboard. Events can also be triggered programmatically using JavaScript code.


const button = document.querySelector("button"); button.addEventListener("click", function() { console.log("I am clicked!"); });

8. What is a callback function in JavaScript?

A callback function is a function that is passed as an argument to another function and is executed after the parent function has been completed. Callback functions are often used in asynchronous programming to ensure that certain tasks are completed before proceeding to the next step.

9. What is a closure in JavaScript?

A closure is a function that has access to variables in its parent scope even after the parent function has returned. Closures are commonly used in JavaScript for encapsulating data and abstracting details of implementation.

10. What is the purpose of "strict mode" in JavaScript?

Strict mode is a feature of JavaScript that enables developers to write code in a "strict" manner, which adds additional checks and controls to the language. It helps prevent errors by offering warnings when certain features of the language are used incorrectly. Strict mode also makes certain optimizations possible, improving performance and security.


Advanced-Level JavaScript Interview Questions and Answers

11. What is prototypal inheritance in JavaScript?

Prototypal inheritance is a feature of JavaScript that allows objects to inherit directly from other objects.

Every object in JavaScript has a prototype object, which is a reference to another object. When a property or method is accessed on an object, JavaScript first looks for that property or method on the object itself. If the property or method is not found on the object, JavaScript then looks for it on the object's prototype object. If the property or method is still not found, JavaScript continues up the prototype chain until it reaches the top-level Object.prototype object.

12. What is a module in JavaScript and how do you create one?

In JavaScript, a module is a self-contained unit of code that encapsulates related functionality and provides an interface for other code to interact with. Modules can help to keep code organized, reduce namespace collisions, and improve code reusability.


// math.js module export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b;

In this example, we use the export keyword to export the add and subtract functions from the math.js module. To use this module in another file, we can import it using the import keyword.

13. What is the difference between "call" and "apply" in JavaScript?

The call() and apply() methods are used to invoke a function with a given "this" value and arguments. The difference between the two methods is that call() accepts an argument list, while apply() accepts an array of arguments. Both can be used to change the context of a function invocation, which allows for some interesting use cases such as borrowing methods from other objects.

14. What is a higher-order function in JavaScript?

A higher-order function is a function that takes one or more functions as parameters and/or returns a function. Higher-order functions are often used to create more abstract and reusable pieces of code that can be used in different contexts.

Examples of higher-order functions include map(), filter(), and reduce().

15. What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code is executed in the order that it appears in the source code, while asynchronous code is executed at a later time or on a different thread.

Asynchronous code can be used to improve performance by allowing certain tasks to happen concurrently and without blocking the execution of other code.

16. What is the difference between a Promise and a Callback in JavaScript?

Promises and callbacks are both mechanisms for dealing with asynchronous code in JavaScript. The primary difference is that promises offer a better way to handle errors, as well as provide an easier-to-read syntax compared to callbacks. Promises also allow for chaining multiple asynchronous operations together which makes handling complex sequences of operations much easier.

17. What is the difference between "null" and "undefined" in JavaScript?

In JavaScript, null and undefined are two distinct values that represent the absence of a value.

The main difference between the two is that null is an assignment value, while undefined indicates that a variable has not been assigned a value. Additionally, null can be explicitly used to indicate the absence of a value, while undefined cannot.

18. What is event bubbling in JavaScript?

Event bubbling is a feature of the DOM (Document Object Model) that allows events to propagate up through the DOM tree. This can be useful in cases where you want an event on a parent element to trigger actions on its child elements.

19. What is the difference between "document" and "window" in JavaScript?

The document is the actual web page being displayed in a browser, while the window object represents an instance of a browser. The document object provides access to the content of a web page, while the window object allows you to interact with the user's browser and control how it behaves.


// Select an element by ID and change its text document.getElementById('myElement').textContent = 'Hello, world!'; // Open a new browser window'', '_blank');

20. What is the purpose of the "use strict" directive in JavaScript?

The "use strict" directive is used to enforce stricter parsing and error handling in JavaScript. This helps to avoid errors that can occur due to syntax issues, as well as improve overall code quality. Additionally, this directive also enables certain language features that are not available in regular JavaScript.


Common JavaScript Coding Interview Questions and Answers

21. Write a function to reverse a string in JavaScript.

function reverseString(str) { let reversedStr = ''; for (let i = str.length - 1; i >= 0; i--) { reversedStr += str[i]; } return reversedStr; }

This function takes a string as an argument and uses a for loop to iterate over the characters in the string in reverse order. For each character, it adds the character to a new string called "reversedStr". Finally, it returns the "reversedStr" string.

22. Write a function to find the largest number in an array in JavaScript.

function findLargestNumber(numbers) { let largestNumber = numbers[0]; for (let i = 1; i < numbers.length; i++) { if (numbers[i] > largestNumber) { largestNumber = numbers[i]; } } return largestNumber; }

This function takes an array of numbers as an argument and initializes a variable "largestNumber" to the first number in the array. It then uses a for loop to iterate over the remaining numbers in the array, comparing each number to "largestNumber". If a number is greater than "largestNumber", the function updates the value of "largestNumber" to the new number.

Finally, the function returns the value of "largestNumber", which is the largest number in the array.

23. Write a function to check if a given number is prime in JavaScript.

function isPrime(number) { if (number <= 1) { return false; } for (let i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) { return false; } } return true; }

This function takes a number as an argument and first checks if the number is less than or equal to 1. If the number is 1 or less, the function immediately returns false, since 1 and numbers less than 1 are not considered prime.

If the number is greater than 1, the function uses a for loop to check if the number is divisible by any integer from 2 up to the square root of the number. If the number is divisible by any of these integers, it is not prime, and the function returns false. If the number is not divisible by any of these integers, it is prime, and the function returns true.

24. Write a function to remove duplicates from an array in JavaScript.

function removeDuplicates(array) { return Array.from(new Set(array)); }

This function takes an array as an argument and creates a new Set object using the array. Since sets can only contain unique values, this effectively removes duplicates in the array.

The function then uses the Array.from() method to convert the set back into an array, which it returns as the final result.

25. Write a function to check if two strings are anagrams in JavaScript.

function areAnagrams(string1, string2) { if (string1.length !== string2.length) { return false; } const charCount = {}; for (let char of string1) { charCount[char] = charCount[char] + 1 || 1; } for (let char of string2) { if (!charCount[char]) { return false; } charCount[char]--; } return true; }

This function takes two strings as arguments and first checks if they are the same length. If the strings are not the same length, they cannot be anagrams, and the function returns false.

If the strings are the same length, the function uses an object to count the frequency of each character in the first string. It then loops through the second string, checking if each character exists in the "charCount" object and decrementing the count for that character. If the count for a character in the second string is greater than the count for that character in the first string, or if a character in the second string does not exist in the "charCount" object, the function returns false.

If the function has not returned false by this point, the two strings must be anagrams, and the function returns true.

26. Write a function to find the factorial of a given number in JavaScript.

function factorial(num) {  if (num === 0 || num === 1) {   return 1;  }  let result = num;  for (let i = num - 1; i >= 1; i--) {   result *= i;  }  return result; }

This function takes a number num as an argument and first checks if it is equal to 0 or 1. If so, it returns 1 because the factorial of 0 and 1 is 1.

If num is not equal to 0 or 1, the function initializes a variable result to num and then loops from num - 1 down to 1, multiplying result by each number in the loop. At the end of the loop, result will be the factorial of the original num, and the function returns result.

27. Write a function to sort an array in JavaScript.

There are several ways to sort an array in JavaScript, but one common way is to use the Array.prototype.sort() method. Here's an example function that sorts an array of numbers in ascending order:

function areAnagrams(string1, string2) { if (string1.length !== string2.length) { return false; } const charCount = {}; for (let char of string1) { charCount[char] = charCount[char] + 1 || 1; } for (let char of string2) { if (!charCount[char]) { return false; } charCount[char]--; } return true; }

This function takes an array as an argument and uses the sort() method to sort the elements of the array in ascending order. The sort() method sorts the elements of an array in place and returns the sorted array.

The sort() method takes a comparison function as an optional argument. In this example, we pass a comparison function that subtracts b from a. This comparison function tells the sort() method to sort the elements in ascending order.

28. Write a function to implement a stack in JavaScript.

In JavaScript, you can implement a stack using an array and the push() and pop() methods. Here's an example function that implements a stack:

function Stack() { this.items = []; } Stack.prototype.push = function(element) { this.items.push(element); }; Stack.prototype.pop = function() { if (this.items.length === 0) { return "Underflow"; } return this.items.pop(); }; Stack.prototype.peek = function() { return this.items[this.items.length - 1]; }; Stack.prototype.isEmpty = function() { return this.items.length === 0; }; Stack.prototype.print = function() { console.log(this.items.toString()); };

This function defines a Stack object with the following methods:

  • push(element): adds an element to the top of the stack.
  • pop(): removes and returns the top element of the stack. If the stack is empty, returns "Underflow".
  • peek(): returns the top element of the stack without removing it.
  • isEmpty(): returns true if the stack is empty, false otherwise.
  • print(): prints the contents of the stack.

29. Write a function to implement a queue in JavaScript.

class Queue { constructor() { this.items = []; } enqueue(element) { this.items.push(element); } dequeue() { if (this.isEmpty()) { return "Queue is empty"; } return this.items.shift(); } front() { if (this.isEmpty()) { return "Queue is empty"; } return this.items[0]; } isEmpty() { return this.items.length === 0; } size() { return this.items.length; } print() { console.log(this.items); } }

In this example, the enqueue method adds an element to the end of the queue, the dequeue method removes and returns the element at the front of the queue, the front method returns the element at the front of the queue without removing it, the isEmpty method checks if the queue is empty, the size method returns the number of elements in the queue, and the print method logs the contents of the queue to the console.

30. Write a function to implement binary search in JavaScript.

function binarySearch(arr, value) { let low = 0; let high = arr.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); const guess = arr[mid]; if (guess === value) { return mid; } if (guess > value) { high = mid - 1; } else { low = mid + 1; } } return -1; }

In this example, the binarySearch function takes an array and a value to search for as parameters. It uses a while loop to repeatedly divide the array in half and check if the value is in the left or right half. If the value is found, the function returns the index of the value in the array. If the value is not found, the function returns -1.

31. Write a function to implement bubble sort in JavaScript.

function bubbleSort(arr) { const len = arr.length; for (let i = 0; i < len; i++) { for (let j = 0; j < len - i - 1; j++) { if (arr[j] > arr[j + 1]) { // swap elements const temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }

In this example, the bubbleSort function takes an array as a parameter and uses two nested loops to compare adjacent elements and swap them if they are in the wrong order. The outer loop controls how many times the inner loop runs and the inner loop compares each pair of adjacent elements. The function continues swapping elements until the entire array is sorted. Finally, the function returns the sorted array.

32. Write a function to implement quick sort in JavaScript.

function quickSort(arr) { if (arr.length <= 1) { return arr; } const pivot = arr[Math.floor(Math.random() * arr.length)]; const left = []; const right = []; for (let i = 0; i < arr.length; i++) { if (arr[i] < pivot) { left.push(arr[i]); } else if (arr[i] > pivot) { right.push(arr[i]); } } return [...quickSort(left), pivot, ...quickSort(right)]; }

In this example, the quickSort function takes an array as a parameter and recursively divides the array into two sub-arrays around a randomly chosen pivot element. The left array contains all elements less than the pivot, and the right array contains all elements greater than the pivot. Finally, the function concatenates the sorted left sub-array, the pivot, and the sorted right sub-array to produce the final sorted array.

Note that this implementation uses the ES6 spread operator to concatenate arrays, but you can also use the concat() method or other approaches to achieve the same result.

33. Write a function to implement a linked list in JavaScript.

class ListNode { constructor(val) { this.val = val; = null; } } class LinkedList { constructor() { this.head = null; this.size = 0; } addAtHead(val) { let node = new ListNode(val); = this.head; this.head = node; this.size++; } addAtTail(val) { let node = new ListNode(val); if (!this.head) { this.head = node; } else { let current = this.head; while ( { current =; } = node; } this.size++; } get(index) { if (index < 0 || index >= this.size) return -1; let current = this.head; for (let i = 0; i < index; i++) { current =; } return current.val; } deleteAtIndex(index) { if (index < 0 || index >= this.size) return; if (index === 0) { this.head =; } else { let current = this.head; for (let i = 0; i < index - 1; i++) { current =; } =; } this.size--; } }

This implementation uses a ListNode class to represent a node in the linked list, and a LinkedList class to represent the entire list. The LinkedList class has methods to add nodes at the head or tail of the list, get the value of a node at a specific index, and delete a node at a specific index.

34. Write a function to implement a binary tree in JavaScript.

class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } class BinaryTree { constructor() { this.root = null; } insert(value) { let node = new Node(value); if (this.root === null) { this.root = node; } else { this._insertNode(this.root, node); } } _insertNode(currentNode, newNode) { if (newNode.value < currentNode.value) { if (currentNode.left === null) { currentNode.left = newNode; } else { this._insertNode(currentNode.left, newNode); } } else { if (currentNode.right === null) { currentNode.right = newNode; } else { this._insertNode(currentNode.right, newNode); } } } search(value) { return this._searchNode(this.root, value); } _searchNode(currentNode, value) { if (currentNode === null) { return false; } else if (value === currentNode.value) { return true; } else if (value < currentNode.value) { return this._searchNode(currentNode.left, value); } else { return this._searchNode(currentNode.right, value); } } }

In this example, we define a Node class to represent each node in the binary tree, with a value property and left and right child nodes. We also define a BinaryTree class with methods to insert nodes into the tree and search for a specific value.

The _insertNode method is a helper function to recursively traverse the tree to find the correct position to insert a new node based on its value. The _searchNode method similarly recursively searches the tree for a specific value.

35. Write a function to implement breadth-first search in a binary tree in JavaScript.

function breadthFirstSearch(root) { if (!root) return []; const queue = [root]; const result = []; while (queue.length > 0) { const current = queue.shift(); result.push(current.value); if (current.left) queue.push(current.left); if (current.right) queue.push(current.right); } return result; }

This function takes in the root node of a binary tree and performs a breadth-first search. It initializes a queue with the root node and an empty result array. Then it enters a while loop, where it dequeues the first element in the queue (the current node), adds its value to the result array, and enqueues its left and right children (if they exist).

This process continues until the queue is empty, at which point the function returns the result array containing the breadth-first search traversal of the binary tree.

36. Write a function to implement depth-first search in a binary tree in JavaScript.

function dfs(node) { if (!node) { return; } console.log(node.value); if (node.left) { dfs(node.left); } if (node.right) { dfs(node.right); } }

This function takes a node in a binary tree as an argument and performs a depth-first search, printing out the value of each node visited. It first checks if the current node is null, and if so, it returns. Otherwise, it logs the value of the current node to the console. Then, it recursively calls itself on the left and right child nodes of the current node, if they exist.

There are different types of depth-first search algorithms, such as pre-order, in-order, and post-order traversal, which differ in the order in which nodes are visited. The above function uses a pre-order traversal, which visits the current node, then its left child, and then its right child.

37. Write a function to compare two binary trees in JavaScript.

function compareTrees(tree1, tree2) { // check if both trees are empty if (!tree1 && !tree2) { return true; } // check if both trees are not empty if (tree1 && tree2) { // check if the values of the nodes are equal if (tree1.val === tree2.val) { // recursively compare the left and right subtrees return compareTrees(tree1.left, tree2.left) && compareTrees(tree1.right, tree2.right); } } // if any of the above conditions are not met, return false return false; }

In this function, tree1 and tree2 are the two binary trees to be compared. The function first checks if both trees are empty, in which case it returns true.

If both trees are not empty, it checks if the values of their root nodes are equal. If the values are equal, it recursively compares the left and right subtrees of both trees using the same function. If any of the above conditions are not met, the function returns false.


Topics: Javascript

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about the differences between and uses of these popular programming languages.