SOLFIND
Web Lens
Portal home

Top 80 JavaScript Coding Interview Questions and Answers

https://roadmap.sh/questions/javascript-coding • 202 KB fetched
Open original page


Top 80 JavaScript Coding Interview Questions and Answers AI Tutor
*
Roadmaps
* AI Tutor
Lesson Packs Newsletters

Loading...

Top 80 JavaScript Coding Interview Questions and Answers
Fernando Doglio Prefer us on Google
Just like its ecosystem, the world of JavaScript coding interview questions is constantly evolving. As the wonderful programming language that it is, JavaScript is used to create everything from dynamic web pages to complex web servers.
If you’re looking for a JavaScript developer role, once you have a solid knowledge of the language (our JavaScript roadmap is a great place to get started), being prepared for these interviews is crucial to your success. And if you’re a hiring manager, having a great set of questions is just as critical.
In this Article
* Getting Ready for the Interview

* Test yourself with Flashcards

* Questions List

In this article, you’ll find a very detailed list of questions designed to test a developer’s practical skills in JavaScript.
Getting Ready for the Interview
Before diving into the questions, it’s important to understand what interviewers are looking for.
They want to see how you solve problems, how you face the unknown, and the thought process behind your solutions.
They’ll want to understand how you think about data structures and how you approach real-world scenarios. How do you apply those theoretical tools to solve actual problems?
On top of that, remember to review your basic JavaScript concepts and practice writing clean, efficient code. In the end, you’ll be doing that every day.
You should be comfortable with everything from the const keyword to how a callback function works. Remember: don't just memorize solutions; understand the core principles.
Test yourself with Flashcards
You can either use these flashcards or jump to the questions list section below to see them in a list format.

0 / 80
Knew 0 Items Learnt 0 Items Skipped 0 Items Reset Progress

Beginner questions
What is the difference between var, let, and const?

Click to Reveal the Answer

var has a global scope or function scope; let and const are block-scoped.
var can be re-declared and updated, let can be updated but not re-declared.
Finally, const cannot be re-declared or updated, that’s why they’re called “constants”.

Hide the Answer

Already Know that Didn't Know that Skip Question

Questions List
If you prefer to see the questions in a list format, you can find them below.
Beginner questions
What is the difference between var, let, and const?
var has a global scope or function scope; let and const are block-scoped.
var can be re-declared and updated, let can be updated but not re-declared.
Finally, const cannot be re-declared or updated, that’s why they’re called “constants”.

Write a function sumArray(arr) that returns the sum of all the elements in an input array.
You can use the reduce method for this:
javascript

function sumArray(arr) { return arr.reduce((acc, current) => acc + current, 0); }

This method will apply the “accumulator” function to every element of the array, receiving the current accumulated value (the result from the last call of the function) as the first parameter and the current value being processed as the second one. The “0” in the above code simply defines the initial value for the accumulator variable.

How do you check if a given string is a palindrome? Write a function isPalindrome to demonstrate.
A simple isPalindrome function could take a given string, reverse it, and compare it to the original.
javascript

function isPalindrome(str) { return str === str.split('').reverse().join(''); }

Since there is no direct way to reverse a string in JavaScript, what we’re doing is turning the string into an array of characters and reversing that. We then join all those values into a single string to compare it with the original input.

Explain type coercion in JavaScript. Give an example.
Type coercion is JavaScript’s automatic conversion of values from one data type to another.
For example, '5' + 5 results in '55' , as the number 5 is coerced into a string when trying to add a number and a string.

Write a function that reverses a given string. A simple function reversestring should suffice.
You can write a simple reversestring function like this:
javascript

function reversestring(str) { return str.split('').reverse().join(''); }

You first split the string into an array of characters, reverse it, and then re-join all characters together. The resulting string is the reversed version of the original one.

How do you find the maximum difference between any two elements in an input array?
You can solve this one by iterating over the input array and calculating the max and min values at the same time. At the end, you can return the difference between those values.
Here’s a sample implementation:
javascript

function findMaxDifference(arr) { // Check if the array has at least two elements. if (arr.length < 2) { return 0; } // Initialize both min and max values with the first element of the array. let minVal = arr[0]; let maxVal = arr[0]; // Iterate through the array starting from the second element in a single pass. for (let i = 1; i < arr.length; i++) { // Check if the current element is smaller than the current minimum value. if (arr[i] < minVal) { minVal = arr[i]; } else if (arr[i] > maxVal) { maxVal = arr[i]; } } // The result is the difference between the maximum and minimum values found. return maxVal - minVal; }

Write a function that checks if a given number is prime. Name your function isprime.
A function isprime checks if a number is divisible by any integer from 2 up to the square root of the number. If it finds one, it should return false. Here’s a potential implementation for this function:
javascript

function isprime(num) { // Prime numbers are natural numbers greater than 1. if (num <= 1) { return false; } // 2 is the only even prime number. if (num === 2) { return true; } // If the number is even and greater than 2, it's not prime. if (num % 2 === 0) { return false; } // Check for divisibility from 3 up to the square root of the number. // We can skip even numbers by incrementing by 2. for (let i = 3; i <= Math.sqrt(num); i += 2) { // If the number is divisible by i, it's not prime. if (num % i === 0) { return false; } } // If no divisors are found, the number is prime. return true; }

Given a var c = 10 in the global scope, what happens if you declare var c = 20 inside a function?
The var c = 20 inside the function will be locally scoped, so the variable in the global scope will remain 10.

How do you check if a data type is an object type?
You can use typeof obj === 'object' && obj !== null .
The null check is important because typeof null also returns 'object' .

Write a function factorial(n) to calculate the factorial of a number using a recursive function.
A recursive function is one that calls itself, and we can write a function that follows this principle and calculates the factorial of a number, like this:
javascript

function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); }

How would you iterate over all elements inside of an array and add them to a new empty array?
You would use a for loop. For each of the elements, you would use newArray.push(element) to add it to a new empty array.

Explain the difference between null and undefined.
These two terms are usually confused with each other.
undefined means a variable has been declared but not assigned a value. null is a value that can be assigned to a variable to explicitly indicate a non-value or empty string.

How would you write a function removeFalsyValues(arr) that removes falsy values from an array?
Falsy values are values that, once coerced, will evaluate to “false”, such as 0 or an empty array.
A removeFalsyValues function can be a simple function that uses the filter method:
javascript

function removeFalsyValues(arr) { return arr.filter(Boolean); }

What are the different ways to declare a function in JavaScript?
There are three main ways to declare a function in JavaScript:

* As a function declaration with the function keyword: function myFunciton(..) {...}

* As an arrow function: const myFunction = () => {}

* Using the Function object: const myFunction = new Function(...)

Write a function that returns the Fibonacci sequence up to a certain number.
One potential implementation of this function could look like this:
javascript

function fibonacciSequence(n) { // Handle edge cases for n < 2. if (n <= 0) { return []; } else if (n === 1) { return [0]; } // Initialize the sequence with the first two numbers. const sequence = [0, 1]; // Use a loop to generate the remaining numbers. for (let i = 2; i < n; i++) { // Each new number is the sum of the previous two numbers in the sequence. const nextNumber = sequence[i - 1] + sequence[i - 2]; sequence.push(nextNumber); } // Return the resulting Fibonacci sequence. return sequence; }

How can you convert an array of objects into a single object?
You can use the reduce() method to convert an array of objects into a single object. This approach is very effective because it iterates over the array and accumulates a single value (in this case, a new object).
The reducer function takes two arguments: the accumulator and the current item. You build the final object by adding a new key-value pair for each item in the original array.
This method is concise and is often preferred in modern JavaScript.
Let’s take a look at a potential implementation:
javascript

function convertArrayToObject(arr) { return arr.reduce((accumulator, currentItem) => { const key = currentItem.id; const value = currentItem.value; accumulator[key] = value; return accumulator; }, {}); // The `{}` is the initial value of the accumulator. }

In this approach, the reduce() method iterates over the array. The first argument is a function that takes the accumulator and the current item. The second argument {} is the initial value of our accumulator, an empty object.
On every iteration, we get the key and value from the current item (assuming each item has a unique id and a value property), and we add a new property to the accumulator with the current item's key and value.
javascript

// Example usage: const data = [ { id: 'a', value: 1 }, { id: 'b', value: 2 }, { id: 'c', value: 3 } ]; const singleObject = convertArrayToObject(data); console.log(singleObject); // Expected output: { a: 1, b: 2, c: 3 }

Explain the purpose of a callback function.
A callback function is a JavaScript function that's passed as an argument to another function. The purpose is to have the outer function execute the callback function at a specific point in time or after a particular action is completed, usually an asynchronous one.
This pattern is one of the key patterns in asynchronous JavaScript programming, allowing blocking operations to be executed without blocking the rest of your code (operations like I/O reads, external API calls, etc).

What is the difference between map, filter, and reduce?
map creates a new array by applying a function (usually a transformation) to each element of the original array.
filter creates a new array containing only array elements that pass a test (executed by a function passed as a parameter).
reduce reduces all the elements of an array to a single value.

How do you find the unique elements in an array with duplicate elements? Write a function removeDuplicates(arr) that does this.
A removeDuplicates function can benefit from the concept of a Set , which doesn’t allow for duplicate values inside it.
javascript

function removeDuplicates(arr) { return [...new Set(arr)]; }

This function initializes a new Set with the values of the array, by default limiting its content to unique values and then returns a newly formed array using the spread operator (the “...”)

Write a function areAnagrams(str1, str2) that checks if two strings are anagrams of each other.
An areAnagrams function should check if the sorted versions of two strings are identical.
javascript

function areAnagrams(str1, str2) { return str1.split('').sort().join('') === str2.split('').sort().join(''); }

This way you avoid having to iterate over the characters, simply sort both of them and check the results.

What is the spread operator, and when is it useful?
The spread operator ( ... ) expands an iterable (like an array) into its individual elements. It's useful for merging arrays or creating copies (as seen in action in question #19).

Write a function to find the largest number in a mixed input array of numbers and strings.
You can use the filter method to create a new array with only numbers. Then, use return Math.max(...numbers) to find the largest number. Here we’re using the spread operator again to provide the values of the array as individual parameters of the Math.max method.

Explain Hoisting in JavaScript.
In JavaScript, hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means you can use a variable or call a function before it's "officially" declared in your code.
That said, it’s important to understand a very specific detail: only the declarations are hoisted, not the initializations.
For instance, a variable declared with var can be "used" before its declaration, but its value will be undefined until the code reaches the line where it's assigned. This is a common source of bugs in javascript programming.
On the other hand, let and const declarations are also hoisted, but they exist in a "temporal dead zone" from the start of the block until they are declared, and attempting to access them will throw an error. This behavior makes let and const safer and more predictable.

How do you merge two arrays into a single array without using concat()? Write a function called mergeArrays.
A mergeArrays function can use the spread operator:
javascript

function mergeArrays(arr1, arr2) { return [...arr1, ...arr2]; }.

This way, the content of both arrays is spread as individual values inside the new array, no need to iterate manually over the arrays or anything.

How do you stringify a JavaScript object into a JSON string?
You use JSON.stringify(obj) to convert a JavaScript object or value to a JSON string.

How do you create an empty string?
You can declare a variable and assign it "" or use String() .

Write a function converts(arr) that converts an array of strings to a single string separated by spaces.
A converts function can be written like this:
javascript

function converts(arr) { return arr.join(' '); }.

How would you get a new array from an original array with all elements doubled?
To solve this, you can use a map method call like this:
javascript

const doubled = originalArray.map(item => item * 2);.

The map method returns a new array by default, so you can solve both problems at the same time.

How can you check if an array includes a specific element?
You can use the includes() method, which is a simple function that returns true or false .

What is a JavaScript function?
A JavaScript function is a block of code designed to perform a particular task. It can be called repeatedly throughout your code..

Mid-Level questions
How do you implement a function to debounce a series of function calls?
A debounce function is a JavaScript function that limits the rate at which another function can be called.
It typically takes advantage of both the setTimeout and clearTimeout functions to prevent a series of function calls from all firing at once.

What is the event loop, and how does it relate to asynchronous JavaScript?
The event loop is a crucial part of the JavaScript runtime architecture, it helps to handle asynchronous operations.
The event loop constantly checks if the call stack is empty and pushes tasks from the task queue onto it.

Explain the difference between a function declaration and a function expression.
They’re both ways for you to define a function, however:

* A function declaration is hoisted, meaning you can call it before it is declared.

* A function expression, on the other hand, is not hoisted, so you must define it before you can call it.

How does the this keyword work in a regular JavaScript function versus an arrow function?
A regular JavaScript function sets its own this keyword based on how it's called, and you can use it to reference itself. An arrow function, however, does not have its own this keyword; it inherits its scope (what the this keyword references) from the enclosing scope.

How would you create a private variable using a JavaScript function? Show a function that returns a function or object with methods.
You can use a closure to achieve this. A function that returns a function or an object with a method can access a variable from its parent scope.
javascript

function createCounter() { // `count` is the private variable. It is only accessible within this function. let count = 0; // The function returns an object with methods. // These methods are the only way to interact with the private `count` variable. return { // The `increment` method has access to `count` through the closure. increment: function() { count++; console.log(`Count incremented to: ${count}`); }, // The `getValue` method also has access to `count`. getValue: function() { return count; } }; }

Write a function that takes an obj and a key, and returns the value of that key.
javascript

function getValueByKey(obj, key) { // Check if the object and key are valid and the object has the key as its own property. // We use `Object.prototype.hasOwnProperty.call()` for a safer check // against objects that might not have a `hasOwnProperty` method. if (typeof obj === 'object' && obj !== null && Object.prototype.hasOwnProperty.call(obj, key)) { return obj[key]; } else { // If the key doesn't exist or the inputs are invalid, return undefined. return undefined; } }

Explain Closures and provide an exa

Links found on this page

  1. AI Tutor [direct]
  2. Roadmaps [direct]
  3. Lesson Packs [direct]
  4. Newsletters [direct]
  5. Fernando Doglio [direct]
  6. Prefer us on Google [direct]
  7. JavaScript roadmap [direct]
  8. Getting Ready for the Interview [direct]
  9. How Long Does It Take to Learn JS? A Career Seeker's Guide [direct]
  10. Is JavaScript Hard to Learn? Advice from a Pro [direct]
  11. TypeScript vs JavaScript: Which to Choose For Your Project [direct]
  12. 6th most starred project on GitHub [direct]
  13. Star us on GitHub Help us reach #1 [direct]
  14. Register yourself Commit to your growth [direct]
  15. Join on Discord Join the community [direct]
  16. Guides [direct]
  17. FAQs [direct]
  18. YouTube [direct]
  19. roadmap.sh [direct]
  20. @nilbuild @nilbuild [direct]
  21. Terms [direct]
  22. Privacy [direct]
  23. DevOps [direct]
  24. Kubernetes [direct]
  25. Cloud-Native [direct]