Top 72 Swift Interview Questions

25+ JavaScript Coding Interview Questions (SOLVED with CODE)

Having a JavaScript Coding Interview Session on this week? Fear not, we got your covered! Check that ultimate list of 25 advanced and tricky JavaScript Coding Interview Questions and Challenges to crack on your next senior web developer interview and got your next six-figure job offer in no time!

Q1 :   Explain what a callback function is and provide a simple example

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

Q2 :   Given a string, reverse each word in the sentence

For example Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG

Q3 :   How to check if an object is an array or not? Provide some code.

The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding this let say we have a method called greet which take one single string and also a list of string, so making our greet method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value?

However, in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see below code for the same.

Now it's fine we can go with above two implementations, but when we have a situation like a parameter can be single value , array , and object type then we will be in trouble.

Coming back to checking type of object, As we mentioned that we can use Object.prototype.toString

If you are using jQuery then you can also used jQuery isArray method:

FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

In modern browser, you can also use:

Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

Q4 :   How to empty an array in JavaScript?

How could we empty the array above?

Above code will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList .

For Instance:

Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the another reference variable which pointing to arrayList .

Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

Above implementation can also empty the array. But not recommended to use often.

Q5 :   How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

Q6 :   Implement enqueue and dequeue using only two stacks

Enqueue means to add an element, dequeue to remove an element.

Q7 :   Make this work

Q8 :   write a "mul" function which will properly when invoked as below syntax.

Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive

In JavaScript function defined inside has access to outer function variable and function is the first class object so it can be returned by function as well and passed as argument in another function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • Function can be stored as variable
  • Function can be pass as a parameter to another function
  • Function can be returned from function

Q9 :   Write a function that would allow you to do this?

You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber .

Q10 :   FizzBuzz Challenge

Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3 , "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5 .

Check out this version of FizzBuzz:

Q11 :   Given two strings, return true if they are anagrams of one another

For example: Mary is an anagram of Army

Q12 :   How would you use a closure to create a private counter?

You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.

Q13 :   Provide some examples of non-bulean value coercion to a boolean one

The question is when a non-boolean value is coerced to a boolean, does it become true or false , respectively?

The specific list of "falsy" values in JavaScript is as follows:

  • "" (empty string)
  • 0 , -0 , NaN (invalid number)
  • null , undefined

Any value that's not on this "falsy" list is "truthy." Here are some examples of those:

  • [ ] , [ 1, "2", 3 ] (arrays)
  • { } , { a: 42 } (objects)
  • function foo() { .. } (functions)

Q14 :   What will be the output of the following code?

Above code would give output 1undefined . If condition statement evaluate using eval so eval(function f() {}) which return function f() {} which is true so inside if statement code execute. typeof f return undefined because if statement code execute at run time, so statement inside if condition evaluated at run time.

Above code will also output 1undefined .

Q15 :   What will the following code output?

The code above will output 5 even though it seems as if the variable was declared within a function and can't be accessed outside of it. This is because

is interpreted the following way:

But b is not declared anywhere in the function with var so it is set equal to 5 in the global scope .

Q16 :   Write a function that would allow you to do this

You can create a closure to keep the value of a even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable a .

Q17 :   How does the this keyword work? Provide some code examples

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

Q18 :   How would you create a private variable in JavaScript?

To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example:

To access the variable, a helper function would need to be created that returns the private variable.

Q19 :   What is Closure in JavaScript? Provide an example

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.

The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace

innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace .

Output of above code would be:

Q20 :   What will be the output of the following code?

Above code will output 0 as output. delete operator is used to delete a property from an object. Here x is not an object it's local variable . delete operator doesn't affect local variable.

Q21 :   What will be the output of the following code?

Above code will output xyz as output. Here emp1 object got company as prototype property. delete operator doesn't delete prototype property.

emp1 object doesn't have company as its own property. You can test it like:

However, we can delete company property directly from Employee object using delete Employee.company or we can also delete from emp1 object using __proto__ property delete emp1.__proto__.company .

Q22 :   What will the following code output?

This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

Q23 :   When would you use the bind function?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

A good use of the bind function is when you have a particular function that you want to call with a specific this value. You can then use bind to pass a specific object to a function that uses a this reference.

Q24 :   Write a recursive function that performs a binary search

Q25 :   describe the revealing module pattern design pattern.

A variation of the module pattern is called the Revealing Module Pattern . The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:

An obvious disadvantage of it is unable to reference the private methods

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

javascript problem solving questions and answers

Top 50 JavaScript Interview Questions With Example Answers

javascript problem solving questions and answers

Preparing for a JavaScript interview requires a lot of work. It’s important to be well-versed in the fundamentals but you also should have some grasp on how to debug JavaScript code, what some of the advanced functions are and how to build projects in it.

Common JavaScript Interview Questions

  • What are the different data types in JavaScript?
  • What is hoisting in JavaScript?
  • What is the difference between null and undefined?
  • What are closures in JavaScript?
  • What is a callback function in JavaScript?
  • What are promises in JavaScript?
  • What is the purpose of the setTimeout() function in Javascript?
  • How can you check if an array includes a certain value?
  • How can you remove duplicates in an array?
  • What is the purpose of async and await in JavaScript?

Below are some tips for preparing for the interview along with some common questions and answers to help you ace your next interview.

JavaScript Interview Questions and Answers With Examples

JavaScript interview questions range from the basics like explaining the different data types in JavaScript to more complicated concepts like generator functions and async and await. Each question will have answers and examples you can use to prepare for your own interview. 

More on JavaScript How to Use the Ternary Operator in JavaScript

JavaScript Fundamentals

1. what is javascript.

A high-level, interpreted programming language called JavaScript makes it possible to create interactive web pages and online apps with dynamic functionality. Commonly referred to as the universal language, Javascript is primarily used by developers for front-end and back-end work.

2. What are the different data types in JavaScript?

JavaScript has six primitive data types:

It also has two compound data types:

3. What is hoisting in JavaScript?

Hoisting is a JavaScript concept that refers to the process of moving declarations to the top of their scope. This means that variables and functions can be used before they are declared, as long as they are declared before they are used in a function.

For example, the following code will print "Hello, world!" even though the greeting variable is not declared until after the console.log() statement.

JavaScript code printing Hello World using hoisting.

4. What is the difference between null and undefined?

null is an assignment value that represents no value or an empty value , while undefined  is a variable that has been declared but not assigned a value.

JavaScript code outputting null and undefined values.

5. Why do we use the word “ debugger ” in JavaScript?

The word “debugger” is used in JavaScript to refer to a tool that can be used to step through JavaScript code line by line. This can be helpful for debugging JavaScript code, which is the process of finding and fixing errors in JavaScript code. To use the debugger , you need to open the JavaScript console in your browser. Then, you can use  debugger commands to comb through your code line by line.

It's essential to know debugging techniques as well as the more general ideas behind code optimization and speed improvement. In addition to operating smoothly, efficient code significantly enhances the user experience.

For example, the following code will print the value of the x variable at each step of the debugger .

JavaScript debugger code printing the value of x at each step.

6. What is the purpose of the “ this”   keyword in JavaScript?

The this  keyword refers to the object that is executing the current function or method. It allows access to object properties and methods within the context of that object.

JavaScript code using the this keyword to output user name.

7. What is the difference between == and === operators in JavaScript?

The equality  ==  operator is a comparison operator that compares two values and returns true if they are equal. The strict equality  ===  operator is also a comparison operator, but it compares two values and returns true only if they are equal and of the same type.

For example , the following code will return true, because the values of the x and y variables are equal.

JavaScript equality operator code comparing x and y equal 10

8. What is the difference between “ var” and “ let” keywords in JavaScript?

The var and let keywords are both used to declare variables in JavaScript. However, there are some key differences between the two keywords.

The var keyword declares a global variable, which means that the variable can be accessed from anywhere in the code. The let keyword declares a local variable, which means that the variable can only be accessed within the block of code where it is declared.

JavaScript Let keyword for x equals 10

9. What are closures in JavaScript?

Closures ( closureFn ) are functions that have access to variables from an outer function even after the outer function has finished executing. They “remember” the environment in which they were created.

JavaScript closure code.

10. What is event delegation in JavaScript?

Event delegation is a technique where you attach a single event listener to a parent element, and that event listener handles events occurring on its child elements. It helps optimize performance and reduce memory consumption.

JavaScript event delegation code example.

11. What is the difference between “ let” , “ const” , and “ var” ?

let  and const were introduced in ES6 and have block scope. let is reassignable, and const is  non-reassignable.  var  is function-scoped and can be redeclared and reassigned throughout the function.

JavaScript let, const and var keywords with outputs.

12. What is implicit type coercion in JavaScript?

Implicit type coercion is a JavaScript concept that refers to the process of converting a value from one type to another. I f you try to add a string to a number, JavaScript will implicitly coerce the string to a number before performing the addition operation.

For example, the following code will add the string "10" to the number 5 . This is because JavaScript will implicitly coerce the string "10" to a number before performing the addition operation.

Implicit type coercion code example in JavaScript adding x and y variables.

13. Explain the concept of prototypes in JavaScript.

Prototypes are a mechanism used by JavaScript objects for inheritance. Every JavaScript object has a prototype, which provides properties and methods that can be accessed by that object.

JavaScript prototype code example.

14. What is the output of the following code?

JavaScript code console.log(three plus two plus "seven");

The output will be "57" . The addition operation is performed from left to right, and when a string is encountered, it performs concatenation.

15. How can you clone an object in JavaScript?

There are multiple ways to clone an object in JavaScript. One common method is using the Object.assign()  method or the spread operator (...) .

JavaScript code for cloning an object using object.assign() and ... operators.

More on JavaScript JavaScript Question Mark (?) Operator Explained

Intermediate Concepts

16. what are higher-order functions in javascript.

Higher order functions are functions that can accept other functions as arguments or return functions as their results. They enable powerful functional programming patterns in JavaScript.

JavaScript higher order functions code.

17. What is the purpose of the bind() method in JavaScript?

The bind() method is used to create a new function with a specified this value and an initial set of arguments. It allows you to set the context of a function permanently.

JavaScript bind() method code.

18. What is the difference between function declarations and function expressions?

Function declarations are defined using the function keyword, while function expressions are defined by assigning a function to a variable. Function declarations are hoisted, while function expressions are not.

JavaScript code showing differences between declaration and expression.

19. What are the different types of errors in JavaScript?

JavaScript can throw a variety of errors, including:

  • Syntax errors: These errors occur when the JavaScript code is not syntactically correct.
  • Runtime errors: These errors occur when the JavaScript code is executed and there is a problem.
  • Logical errors: These errors occur when the JavaScript code does not do what it is supposed to do.

20. What is memoization in JavaScript?

Memoization is a technique that can be used to improve the performance of JavaScript code. Memoization works by storing the results of expensive calculations in a cache. This allows the JavaScript code to avoid re-performing the expensive calculations if the same input is provided again.

For example , the following code calculates the factorial of a number. The factorial of a number is the product of all the positive integers from one to the number.

JavaScript code to calculate the factorial of all positive integers from one to a number.

This code can be memoized as follows:

Memoized code for JavaScript factorial.

21. What is recursion in JavaScript?

Recursion is a programming technique that allows a function to call itself. Recursion can be used to solve a variety of problems, such as finding the factorial of a number or calculating the Fibonacci sequence .

The following code shows how to use recursion to calculate the factorial of a number:

JavaScript recursion code to solve for factorial of a number.

22. What is the use of a constructor function in JavaScript?

A constructor function is a special type of function that is used to create objects. Constructor functions are used to define the properties and methods of an object.

The following code shows how to create a constructor function:

Constructor function in JavaScript

23. What is the difference between a function declaration and a function expression in JavaScript?

A function declaration is a statement that defines a function. A function expression is an expression that evaluates to a function. 

The following code shows an example of a function declaration. This code defines a function named factorial. The factorial function calculates the factorial of a number.

JavaScript function declaration code for a factorial function.

The following code shows an example of a function expression:

JavaScript function expression for factorial code.

24. What is a callback function in JavaScript?

A callback function is a function passed as an argument to another function, which is then invoked inside the outer function. It allows asynchronous or event-driven programming.

JavaScript code for the callback function

25. What are promises in JavaScript?

Promises are objects used for asynchronous operations. They represent the eventual completion or failure of an asynchronous operation and allow chaining and handling of success or error cases.

JavaScript promises code example.

26. What is the difference between synchronous and asynchronous programming?

In synchronous programming, the program execution occurs sequentially, and each statement blocks the execution until it is completed. In asynchronous programming, multiple tasks can be executed concurrently, and the program doesn’t wait for a task to finish before moving to the next one.

Synchronous coding example:

JavaScript synchronous code example

Asynchronous code example:

Asynchronous JavaScript code example.

27. How do you handle errors in JavaScript?

Errors in JavaScript can be handled using try - catch blocks. The try block contains the code that may throw an error, and the catch block handles the error and provides an alternative execution path.

JavaScript try-catch blocks of code.

28. Explain the concept of event bubbling in JavaScript.

Event bubbling is the process where an event triggers on a nested element, and then the same event is propagated to its parent elements in the document object model (DOM) tree. It starts from the innermost element and goes up to the document root.

JavaScript code with event bubbling.

When you click on the child element, both the child and parent event handlers will be triggered, and the output will be:

JavaScript code output after clicking on the child element.

29. What are arrow functions in JavaScript?

Arrow functions are a concise syntax for writing JavaScript functions. They have a more compact syntax compared to traditional function expressions and inherit the this value from their surrounding scope.

For example:

JavaScript arrow functions code example.

30. What is the difference between querySelector and getElementById ?

querySelector is a more versatile method that allows you to select elements using CSS -like selectors, while getElementById specifically selects an element with the specified ID.

JavaScript code comparing querySelector and getElementByID methods.

31. What is the purpose of the setTimeout() function in JavaScript?

The setTimeout() function is used to delay the execution of a function or the evaluation of an expression after a specified amount of time in milliseconds.

JavaScript setTimeout() function code.

Output after two seconds:

JavaScript setTimeout code output after two seconds.

32. What is event delegation and why is it useful?

Event delegation is a technique where you attach a single event listener to a parent element to handle events occurring on its child elements. It’s useful for dynamically created elements or when you have a large number of elements.

JavaScript event delegation code example.

33. How can you prevent the default behavior of an event in JavaScript?

You can use the preventDefault() method on the event object within an event handler to prevent the default behavior associated with that event.

JavaScript preventDefault() method code example.

34. What is the difference between localStorage and sessionStorage in JavaScript?

Both localStorage and sessionStorage are web storage objects in JavaScript, but they have different scopes and lifetimes.

  • localStorage  persists data even after the browser window is closed and is accessible across different browser tabs/windows of the same origin.
  • sessionStorage  stores data for a single browser session and is accessible only within the same tab or window.

JavaScript localStorage and sessionStorage code comparisons.

35. How can you convert a string to lowercase in JavaScript?

You can use the toLowerCase() method to convert a string to lowercase in JavaScript.

JavaScript toLowerCase() code example.

Advanced Concepts

36. what is the purpose of the map() function in javascript.

The map() function is used to iterate over an array and apply a transformation or computation on each element. It returns a new array with the results of the transformation.

JavaScript map() function code example.

37. What is the difference between splice() and slice() ?

  • splice() is used to modify an array by adding, removing, or replacing elements at a specific position.
  • slice() is used to create a new array that contains a portion of an existing array, specified by the starting and ending indices.

Example of splice() :

JavaScript splice() function code example.

Example of slice() :

JavaScript slice() code example.

38. What is the purpose of the reduce() function in JavaScript?

The reduce() function is used to reduce an array to a single value by applying a function to each element and accumulating the result.

JavaScript reduce() function example.

39. How can you check if an array includes a certain value in JavaScript?

You can use the includes() method to check if an array includes a specific value. It returns true if the value is found, and false otherwise.

JavaScript includes() method code on an array.

40. What is the difference between prototype and instance properties in JavaScript?

A prototype property is a property that is defined on the prototype object of a constructor function. Instance properties are properties that are defined on individual objects that are created by a constructor function.

Prototype properties are shared by all objects that are created by a constructor function. Instance properties are not shared by other objects.

41. What is the difference between an array and an object in JavaScript?

An array is a data structure that can store a collection of values. An object is a data structure that can store a collection of properties.

Arrays are indexed by numbers. Objects are indexed by strings.  Arrays can only store primitive data types and objects. Objects can store primitive data types, objects and arrays.

JavaScript differences between array and object code example.

42. How can you remove duplicates from an array in JavaScript?

One way to remove duplicates from an array is by using the Set  object or by using the filter() method with the indexOf() method.

JavaScript code example removing duplicates using the filter() method.

43. What is the purpose of the fetch() function in JavaScript?

The fetch() function is used to make asynchronous HTTP requests in JavaScript. It returns a Promise that resolves to the response from the server.

JavaScript fetch() code function example.

44. What is a generator function in JavaScript?

A generator function is a special type of function that can be paused and resumed during its execution. It allows generating a sequence of values over time, using the yield  keyword.

JavaScript generator function code example.

45. What are the different events in JavaScript?

There are many different events in JavaScript, but some of the most common events include:

  • Click : The click event occurs when a user clicks on an HTML element.
  • Mouseover : The mouseover event occurs when a user's mouse pointer moves over an HTML element.
  • Keydown : The keydown event occurs when a user presses a key on the keyboard.
  • Keyup : The keyup event occurs when a user releases a key on the keyboard.
  • Change : The change event occurs when a user changes the value of an HTML input element.

46. What are the different ways to access an HTML element in JavaScript?

There are three main ways to access an HTML element in JavaScript:

  • Using the getElementById() method: The getElementById() method takes a string as an argument and returns the HTML element with the specified ID.
  • Using the getElementsByTagName() method: The getElementsByTagName() method takes a string as an argument and returns an array of all the HTML elements with the specified tag name.
  • Using the querySelector() method : The querySelector() method takes a CSS selector as an argument and returns the first HTML element that matches the selector.

47. What is the scope of a variable in JavaScript?

The scope of a variable in JavaScript is the part of the code where the variable can be accessed. Variables declared with the var keyword have a local scope, which means that they can only be accessed within the block of code where they are declared. Variables declared with the let keyword have a block scope, which means that they can only be accessed within the block of code where they are declared and any nested blocks. Variables declared with the const keyword have a global scope, which means that they can be accessed from anywhere in the code.

48. What are the different ways to create objects in JavaScript?

There are multiple ways to create objects in JavaScript, including object literals, constructor functions, the Object.create() method and the class syntax introduced in ECMAScript 2015 (ES6).

Example using object literals:

JavaScript object literals code example.

49. What is the purpose of the window object in JavaScript?

The window object represents the browser window. The window object can be used to access the browser’s features, such as the location bar, the status bar and the bookmarks bar.

50. What is the purpose of the async and await keywords in JavaScript?

The async  and await  keywords are used for handling asynchronous operations in a more synchronous-like manner. The async  keyword is used to define an asynchronous function, and the await  keyword is used to pause the execution of an async function until a promise is fulfilled or rejected.

JavaScript async and await function code example.

More on JavaScript JavaScript PreventExtensions Method Explained

How to Prepare for a JavaScript Interview

In order to ace a JavaScript interview, you need to be ready for anything. It’s important to practice your code, but you should also be able to clearly explain how different functions work, have real world experience working in JavaScript and understand how to debug.

7 Ways to Prepare for a JavaScript Interview

  • Review JavaScript fundamentals.
  • Master key concepts.
  • Study common interview questions.
  • Master debugging skills.
  • Practice coding.
  • Build projects.
  • Mock interviews.

Fortunately, there are some basic steps you can take to be prepared and stand out from other applicants. 

1. Review JavaScript Fundamentals 

Make sure you are well-versed in the foundational concepts of JavaScript, such as data types , variables , operators, control structures, functions and objects .

2. Master Key Concepts

It’s also important to study up on key JavaScript topics like promises, asynchronous programming , hoisting, scope, closures, prototypes and ES6 features. You should understand how each of these works.

3. Study Common Interview Topics  

Take the time to review JavaScript interview questions that are regularly asked, including those about closures, prototypes, callbacks, promises, AJAX (asynchronous JavaScript and XML), error handling and module systems. Most interviews follow a similar pattern. Preparing answers for those questions will help you stand out from other candidates.

4. Master Debugging Skills 

Interviewers for JavaScript will often look to assess your code debugging skills. Practice using IDEs or browser developer tools  to find and correct common JavaScript code issues. Learn how to read error messages and review basic debugging techniques.

5. Practice Coding

To develop your coding abilities, complete coding tasks and challenges. Concentrate on standard JavaScript data structures and algorithms such arrays, strings, objects, recursion and sorting techniques.

Online resources like LeetCode , CodeChef and HackerRank can be used to practice coding and get ready for interviews. These websites provide a wide variety of coding puzzles and challenges covering a range of subjects and levels of complexity. They are great resources for developing your coding expertise, problem-solving skills, and algorithmic thinking, all of which are necessary for acing technical interviews.

6. Build Projects 

Take on modest JavaScript projects to get experience and show that you can create useful applications. Showing off your portfolio at the interview is also beneficial. In addition, developers can also work on JavaScript projects to obtain practical experience and show that they are capable of building effective applications. A diversified portfolio can be quite helpful when applying for jobs. Platforms like LeetCode, CodeChef, HackerRank and others enable users to develop projects gradually, starting with minor ones and eventually progressing to more ambitious ones.

7. Mock Interviews 

With a friend or mentor, practice mock interviews paying particular attention to both behavioral and technical components. This enables you to hear useful criticism and become accustomed to the interview process.

It’s not just mastering the technical aspect of JavaScript, it’s about your body language and how you explain your answers. Many companies are also assessing your ability to work within a team and pair program . The better you can explain your actions and thought process, the more likely you’ll be to win over the interviewer.

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Great Companies Need Great People. That's Where We Come In.

download

Precision in Payroll - Acing Taxes and Compliance

Webinar HR Metrics Magic: Transforming Insights into Actions Register Now

  • Interview Questions

Top 50 JavaScript coding Interview Questions and Answers

JavaScript is one of the widely used programming languages and  used to create engaging and dynamic websites. Due to its vast scope, JavaScript interviews can be challenging . However, thorough preparation can help overcome these challenges. An interviewee should familiarize themselves with the most basic concepts to the most complex libraries and frameworks.

These top 50 JavaScript interview questions and answers will help an intervie wee to thoroughly practice and prepare for their interview.  

Top 50 JavaScript Coding Interview Questions  

Basic javascript coding questions.

Basic JavaScript questions cover concepts like data types, variables and scoping, array, string manipulation, OOP (Object Oriented Programming), control flow, error handling, DOM manipulation, and asynchronous programming. The basic JavaScript coding interview questions are:  

1. Write a JavaScript function to calculate the sum of two numbers.    

When managers ask this question, they are looking for the candidate’s basic understanding of JavaScript. They assess their understanding of basic syntax along with problem-solving skills. This also helps evaluate the candidate’s coding style and attention to detail.  

Sample answer: I would take two parameters and the following function can be used to calculate the sum of any 2 numbers that are passed as arguments. 

function sumOfTwoNumbers(a, b) { 

  return a + b; 

2. Write a JavaScript program to find the maximum number in an array.  

A hiring manager asks this question to analyze the candidate’s ability to write clear and efficient code. It’s crucial for candidates to explain the code step-by-step while demonstrating bug-free code.  

Sample answer:  

function findMaxNumber(arr) { 

  return Math.max(…arr); 

3. Write a JavaScript function to check if a given string is a palindrome (reads the same forwards and backwards).  

The interviewer is looking for the candidate’s familiarity with loop constructs, JavaScript string methods, and other basic JavaScript syntax. They will evaluate the candidate’s skills based on the approach used to solve the palindrome problem.  

function isPalindrome(str) { 

  return str === str.split(”).reverse().join(”); 

4. Write a JavaScript program to reverse a given string. 

Hiring managers are expecting an accurate solution that demonstrates the interviewee’s proficiency in JavaScript programming.  

const reverseString = (str) => str.split(”).reverse().join(”); 

 5. Write a JavaScript function that takes an array of numbers and returns a new array with only the even numbers. 

Interviewers are looking for candidates who can not only clearly explain the solution along with the code, but also show the ability to think logically and articulate their thought processes.  

Sample answer: By using the filter method on the array, I can check if each element is even or not by using the modulus operator (%) with 2. The element is even if the result is 0. This can be included in the new array. 

function filterEvenNumbers(numbers) { 

  return numbers.filter(num => num % 2 === 0); 

6. Write a JavaScript program to calculate the factorial of a given number.  

By asking this question, managers aim to assess the candidate’s algorithmic thinking and understanding of JavaScript programming. The interviewer expects the candidate to demonstrate their knowledge of the factorial concept.  

Sample answer: A factorial number is the product of all positive integers, which are equal to or less than the given number.  

function factorial(number) { 

  if (number === 0 || number === 1) { 

    return 1; 

  } else { 

    return number * factorial(number – 1); 

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

Interviewers can analyze the candidate’s knowledge of JavaScript algorithms and mathematical concepts. They expect the candidate to translate a mathematical concept into functional code.  

Sample answer: To check if a given number is prime, loop from 2 to the square root of the number. If any integer evenly divides it, the number is not prime. 

function isPrime(num) { 

  if (num <= 1) return false; 

  for (let i = 2; i <= Math.sqrt(num); i++) { 

    if (num % i === 0) return false; 

  return true; 

8. Write a JavaScript program to find the largest element in a nested array. 

When asking this question, interviewers are looking for the candidate’s ability to handle nested data structures and apply their knowledge of conditional statements, arrays, and loops. Candidates must apply their knowledge to real-world scenarios.  

function findLargestElement(nestedArray) { 

  let largest = nestedArray[0][0]; 

  for (let arr of nestedArray) { 

    for (let num of arr) { 

      if (num > largest) { 

        largest = num; 

  return largest; 

9. Write a JavaScript function that returns the Fibonacci sequence up to a given number of terms. 

This question helps hiring managers assess the interviewee’s understanding of fundamental algorithms in JavaScript. They expect the candidate to consider edge cases and handle errors.  

function fibonacciSequence(numTerms) { 

  if (numTerms <= 0) return []; 

  if (numTerms === 1) return [0]; 

  let sequence = [0, 1]; 

  while (sequence.length < numTerms) { 

    let nextNumber = sequence[sequence.length – 1] + sequence[sequence.length – 2]; 

    sequence.push(nextNumber); 

  return sequence; 

10. Write a JavaScript program to convert a string to title case (capitalize the first letter of each word). 

Interviewers analyze the candidate’s ability to break down a problem into manageable steps and demonstrate knowledge of string manipulation, looping, and basic JavaScript functions.  

function toTitleCase(str) { 

  return str.replace(/\b\w/g, l => l.toUpperCase()); 

A dvanced JavaScript coding interview questions

Advanced JavaScript coding includes various complex concepts and techniques. Such key concepts are often tested in JavaScript interviews. Some of the concepts are – closure and scope, prototypal inheritance, functional programming , design patterns, memory management, ES6+ features, and many more.  

1. Implement a debounce function in JavaScript that limits the frequency of a function’s execution when it’s called repeatedly within a specified time frame.  

Interviewers expect the candidate to showcase their ability to clearly explain the purpose of the debounce function and its usage in scenarios where function calls need to be controlled. They are looking for the person’s ability to articulate technical concepts clearly.  

Sample answer: By delaying the execution of the debounce function until the specified time frame has passed, the frequency can be limited. 

function debounce(func, delay) { 

  let timer; 

  return function() { 

    clearTimeout(timer); 

    timer = setTimeout(func, delay); 

2. Write a function that takes an array of objects and a key, and returns a new array sorted based on the values of that key in ascending order. 

By asking this question, hiring managers analyze how well the candidate can discuss the sorting algorithm and its time complexity. It’s also crucial for candidates to demonstrate their code’s robustness.  

Sample answer: The following function takes an array of objects and a key to sort the array based on the values in ascending order. 

function sortByKey(arr, key) { 

  return arr.sort((a, b) => a[key] – b[key]); 

3. Implement a deep clone function in JavaScript that creates a copy of a nested object or array without any reference to the original. 

Hiring managers want to assess the interviewee’s skill to handle complex coding tasks and understand the concept of avoiding reference issues while cloning.  

Sample answer: By using two methods together and creating a deep clone, I can serialize the object to a JSON string. I would then parse it back into a new object, thereby removing any reference to the original object. 

function deepClone(obj) { 

  return JSON.parse(JSON.stringify(obj)); 

 4. Write a recursive function to calculate the factorial of a given number. 

Interviewers expect the candidate to write a concise recursive function that handles edge cases. Candidates must show their understanding of how recursion works to avoid infinite loops or stack overflow errors.  

function factorial(num) { 

  if (num <= 1) return 1; 

  return num * factorial(num – 1); 

5. Implement a function that takes two sorted arrays and merges them into a single sorted array without using any built-in sorting functions.  

When interviewers ask this question, they seek to assess the knowledge of algorithms and efficiency in handling sorted data. They also look for the ability to think of and execute a correct solution.  

Sample answer: I can implement a function that can efficiently merge two sorted arrays. 

function mergeSortedArrays(arr1, arr2) { 

  return […arr1, …arr2].sort((a, b) => a – b); 

6. Write a function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring case.  

Interviewers analyze the interviewee’s approach to execute code and demonstrate familiarity with handling case-sensitive and alphanumeric checks, regular expressions, and JavaScript string methods.  

  const cleanStr = str.replace(/[^a-zA-Z0-9]/g, ”).toLowerCase(); 

  const reversedStr = cleanStr.split(”).reverse().join(”); 

  return cleanStr === reversedStr; 

7. Create a JavaScript class for a linked list with methods to insert a node at the beginning, end, or at a specific position, and to delete a node from a given position. 

By asking this question, interviewers can evaluate how well a candidate can design and implement a class for a linked list while also presenting their problem-solving skills .  

Sample answer: I would implement a linked list with methods to insert a node at the beginning, end, and at specific positions. Then, I would delete a node from a given position.  

8. Implement a function that flattens a nested array in JavaScript, converting it into a single-level array. 

Managers can gauge the candidate’s logical thinking skills and capability to handle complex data structures. Interviewees should demonstrate their knowledge of loops, recursion, and arrays.  

const flattenArray = (nestedArray) => { 

  return nestedArray.flat(Infinity); 

9. Write a function that determines if two strings are anagrams of each other  

When interviewers present this question, they aim to measure how well the candidate can use appropriate string-related methods and identify anagrams accurately.  

function areAnagrams(str1, str2) { 

  return str1.split(“”).sort().join(“”) === str2.split(“”).sort().join(“”); 

10. Create a JavaScript function that returns the Fibonacci sequence up to a given number, utilizing memoization for optimized performance. 

Interviewees are expected to show their proficiency in OOP and familiarity with recursion and memoization. They can also determine the candidate’s attention to detail in class design and organizing code.  

Sample answer: By creating a function that uses an array to store the computed values, a Fibonacci sequence can be generated. 

function fibonacciWithMemoization(n) { 

  let memo = [0, 1]; 

  for (let i = 2; i <= n; i++) { 

    memo[i] = memo[i – 1] + memo[i – 2]; 

  return memo; 

Common JavaScript coding interview questions  

  Some of the common JavaScript coding interview questions typically cover these topics: checking for palindrome, finding missing/largest numbers, object manipulation, removing duplicates, merging, etc.  

1. Write a function to check if a given string is a palindrome.  

Hiring managers review how well a candidate can handle edge cases while handling case sensitivity, punctuation, and whitespace.  

Sample answer: This function takes a string as input to convert it into lowercase and then compares it with its reverse. The string can be deemed a palindrome if the two match. 

  return str.toLowerCase() === str.toLowerCase().split(”).reverse().join(”); 

2. Implement a function to reverse a string without using the built-in reverse() method.  

Hiring managers aim to analyze the candidate’s knowledge of string manipulation in JavaScript while also measuring their ability to think of alternative solutions.  

Sample answer: I would use a for lopp to iterate through the characters from the end to the beginning. By appending the character to a new string, it results in the reversed output. 

function reverseString(str) { 

  let reversed = ”; 

  for (let i = str.length – 1; i >= 0; i–) { 

    reversed += str[i]; 

  return reversed; 

3. Given an array of numbers, write a function to find the largest and smallest numbers in the array.  

By presenting the candidates with this question, managers can gauge how well a candidate is familiar with basic JavaScript functions and array manipulation.  

Sample answer: I would use the following functions to find the smallest and largest numbers in the array. 

function findMinMax(arr) { 

  let min = Math.min(…arr); 

  let max = Math.max(…arr); 

  return [min, max]; 

4. Write a function that takes an array of integers as input and returns a new array with only the unique elements.  

Hiring managers can evaluate the candidate’s knowledge of JavaScript functions, array handling capabilities, and communicating technical concepts.  

function getUniqueElements(arr) { 

  return Array.from(new Set(arr)); 

5. Implement a function to find the factorial of a given number.  

Interviewers can determine the candidate’s capability to execute functional code and ability to handle input validation and edge cases. Interviewers also assess the ability to use concise and effective code and provide efficient code implementation.  

  if (number === 0 || number === 1) return 1; 

  return number * factorial(number – 1); 

6. Write a function that determines if a given number is prime or not.  

By asking this question, interviewers can understand how good the candidate is proficient in math operations and JavaScript logic. The interviewee should excute a clean and optimized solution that is efficient.  

7. Implement a function to find the sum of all the numbers in an array.  

Such a question helps understand if the interviewee can manipulate arrays and handle numeric values. This also helps managers assess problem-solving capabilities and ability to pay attention to code efficiency.  

Sample answer: I would use the reduce method to implement the following function: 

function findSum(arr) { 

  return arr.reduce((sum, num) => sum + num, 0); 

8. Given a string, write a function to count the occurrences of each character in the string. 

Hiring managers expect the candidate to be familiar with string manipulation and loop constructs. When they ask this question, they can evaluate whether the candidate knows data structures.  

function countCharacterOccurrences(str) { 

  const charCount = {}; 

  for (let char of str) { 

    charCount[char] = (charCount[char] || 0) + 1; 

  return charCount; 

9. Implement a function to remove duplicates from an array.  

When interviewers present the candidate with this question, they can gauge the level of understanding a candidate has regarding array methods and different approaches to solve the problem.  

Sample answer: The following function duplicates from an array by converting it into a Set. This automatically removes duplicates. Next, the function converts the Set back into an array. 

function removeDuplicates(arr) { 

10. Write a function that sorts an array of numbers in ascending order.  

Interviewees must show their knowledge of bubble sort, merge sort, sorting algorithms, and other approaches. The HR manager aims to measure the capability to execute strong algorithms and handle edge cases.  

Sample answer:  I can solve this by using JavaScript’s built-in sort method. 

function ascendingSort(numbers) { 

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

Tricky JavaScript coding questions

By asking tricky JavaScript coding questions, managers can assess problem—solving skills, JavaScript concepts, and critical thinking . These go beyond syntax knowledge and require the candidate to think creatively and logically to solve problems.  

1. Write a function that reverses the order of words in a sentence without using the built-in reverse() method.  

This question not only assesses the creativity of the candidates but also helps hiring managers understand how well a candidate can come up with a clean and understandable solution.  

function reverseSentence(sentence) { 

  const words = sentence.split(‘ ‘); 

  const reversedWords = words.reverse(); 

  return reversedWords.join(‘ ‘); 

2. Implement a function that checks if a given string is a palindrome (reads the same forwards and backwards) while ignoring whitespace and punctuation. 

Interviewers can gauge the interviewee’s capability to handle whitespace and punctuation gracefully while also maintaining the palindrome-checking logic. Candidates must express their knowledge of regular expressions or any other efficient approach.  

  const cleanedStr = str.replace(/[^\w]/g, ”).toLowerCase(); 

  const reversedStr = cleanedStr.split(”).reverse().join(”); 

  return cleanedStr === reversedStr; 

3. Write a function that takes an array of integers and returns the largest difference between any two numbers in the array. 

Candidates should demonstrate their approach to finding the maximum difference between the array elements to handle edge cases and invalid inputs.  

function largestDifference(arr) { 

  let min = arr[0]; 

  let maxDiff = 0; 

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

    if (arr[i] < min) { 

      min = arr[i]; 

      const diff = arr[i] – min; 

      if (diff > maxDiff) { 

        maxDiff = diff; 

  return maxDiff; 

4. Implement a function that removes duplicates from an array, keeping only the unique elements.  

Interviewers can analyze how well a candidate can effectively communicate code explanations and their familiarity with algorithmic efficiency.  

  return arr.filter((item, index) => arr.indexOf(item) === index); 

5. Write a function that accepts a number and returns its factorial (e.g., factorial of 5 is 5 x 4 x 3 x 2 x 1). 

By presenting this question in the interview, hiring managers can assess the capability of the candidate to handle numeric calculations. They can also determine how well the interviewee can pay attention to handling edge cases, if applicable.  

  if (num === 0 || num === 1) { 

    return num * factorial(num – 1); 

6. Implement a function that flattens a nested array into a single-dimensional array. 

Interviewers expect the candidates to demonstrate their ability to work with complex data structures and use appropriate techniques to accomplish tasks.  

function flattenArray(arr) { 

  return arr.flat(); 

7. Write a function that checks if a given string is an anagram of another string (contains the same characters in a different order). 

Candidates should showcase how well they can handle complex algorithms and logic. Interviewers are specifically looking for knowledge in string methods, data structures, and loop constructs.  

 function isAnagram(str1, str2) { 

  const sortedStr1 = str1.split(”).sort().join(”); 

  const sortedStr2 = str2.split(”).sort().join(”); 

  return sortedStr1 === sortedStr2; 

8. Implement a function that finds the second smallest element in an array of integers.  

Interviewers can measure the candidate’s problem-solving skills and their understanding of conditional statements, loops, and arrays.  

function secondSmallest(arr) { 

  const sortedArr = arr.sort((a, b) => a – b); 

  return sortedArr[1]; 

9. Write a function that generates a random alphanumeric string of a given length. 

By asking this question, interviewers can understand how well a candidate can ensure the function produces a reliable and consistent random output.  

function generateRandomString(length) { 

  const characters = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’; 

  let result = ”; 

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

    const randomIndex = Math.floor(Math.random() * characters.length); 

    result += characters.charAt(randomIndex); 

  return result; 

10. Implement a function that converts a number to its Roman numeral representation. 

Hiring managers can gauge a candidate’s capability to implement coding solutions and create an efficient algorithm. 

Sample answers:  

function toRomanNumeral(number) { 

  // Implement your code here 

JavaScript array coding questions

JavaScript array coding interview questions are technical questions asked to gauge candidates’ ability to work with arrays along with their familiarity with fundamental data structures.  

1. Write a function that returns the sum of all numbers in an array.  

By asking such a question, hiring managers can evaluate whether the candidate would be able to perform common tasks and solve basic coding challenges.

Sample answer: 

function sumArray(arr) { 

  return arr.reduce((total, num) => total + num, 0); 

2. Implement a function that finds the maximum number in an array. 

Depending on the candidate’s answer, the manager can determine how effectively the interviewee can work with arrays. The managers can also understand the capability to communicate technical solutions.  

  let max = arr[0]; 

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

    if (arr[i] > max) { 

      max = arr[i]; 

  return max; 

3. Write a function that returns a new array containing only the unique elements from an input array. 

The hiring manager is specifically looking for candidates who can demonstrate an understanding in data manipulation and JavaScript arrays. Additionally, interviewers evaluate how well the candidate strives for an optimized solution without duplicate elements.  

function getUniqueElements(inputArray) { 

  return […new Set(inputArray)]; 

4. Implement a function that returns the average value of numbers in an array. 

By asking this question, hiring managers can assess the candidate’s knowledge of arithmetic operations, array manipulation, and looping.  

function calculateAverage(numbers) { 

  let sum = 0; 

  for (let number of numbers) { 

    sum += number; 

  return sum / numbers.length; 

5. Write a function that sorts an array of strings in alphabetical order. 

When interviewers present this question in the interview, they expect the candidate to be familiar with sorting algorithms and JavaScript array manipulation.  

  Sample answer:  

function sortStrings(arr) { 

  return arr.slice().sort(); 

6. Implement a function that finds the index of a specific element in an array. If the element is not found, the function should return -1. 

Interviewers aim to gauge the candidate’s proficiency in use of array methods, handling edge cases, and in JavaScript syntax. Candidates must implement the function proper error handling.  

function findElementIndex(arr, element) { 

  const index = arr.indexOf(element); 

  return index !== -1 ? index : -1; 

7. Write a function that removes all falsy values (false, null, 0, “”, undefined, and NaN) from an array. 

Candidates must showcase communication skills and explain their solutions logically. Interviewers analyze the interviewee’s ability to write a function that filters false values from an array.

function removeFalsyValues(arr) { 

  return arr.filter(Boolean); 

8. Implement a function that merges two arrays into a single array, alternating elements from each array. 

Hiring managers determine a candidate’s ability to craft efficient algorithms and knowledge of array manipulation.  

function mergeArrays(array1, array2) { 

  const mergedArray = []; 

  const maxLength = Math.max(array1.length, array2.length); 

  for (let i = 0; i < maxLength; i++) { 

    if (i < array1.length) mergedArray.push(array1[i]); 

    if (i < array2.length) mergedArray.push(array2[i]); 

  return mergedArray; 

9. Write a function that finds the second largest number in an array.  

Such a question reveals to the interviewers how well the candidate can use loops and array methods, work with them, and utilize logic to find solutions.  

function findSecondLargest(arr) { 

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

  return arr[1]; 

10. Implement a function that groups elements in an array based on a given condition. For example, grouping even and odd numbers into separate arrays. 

When interviews ask this question, they aim to evaluate a candidate’s understanding of concepts like array methods, conditional statements, and other technical concepts. Candidate should demonstrate good coding style.  

function groupByCondition(arr, condition) { 

  return [ 

    arr.filter(element => condition(element)), 

    arr.filter(element => !condition(element)) 

Tips to prepare for a JavaScript coding interview 

  There are 5 tips a candidate should keep in mind when attending a JavaScript coding interview:  

  • Master JavaScript basics: Candidates must have a solid understanding of core JavaScript fundamentals, including variables, loops, conditionals, objects, and data types. Additionally, practicing coding skills is important.  
  • Explore popular libraries and frameworks: Familiarizing oneself with the most common JavaScript libraries and frameworks like Vue.js, React, etc., helps understand key concepts.  
  • Practice whiteboard Java coding: Java coding skills can further be sharpened by practicing whiteboard coding. Candidates should solve coding challenges and explain their thought processes loudly. They should mainly focus on simplicity, clarity, and efficiency.  
  • Test code : After writing Java solutions, test it with various inputs and ensure it works correctly and can handle edge cases. Consider the time complexity of the solutions and aim for efficiency.  
  • Review JavaScript projects : Discussing JavaScript projects in the interview is essential. Interviewees should explain their approach clearly and how they overcame the challenges.  

There are some red flags hiring managers should watch out for in a JavaScript coding interview:  

  • Lack of basic JavaScript knowledge  
  • Providing inefficient solutions  
  • No practical problem-solving abilities  
  • Limited knowledge of asynchronous programming  
  • Copy-pasting code  
  • Inability to articulate thought processes or provide a clear explanation of their approach to the problem  
  • Unfamiliarity with Modern JavaScript  
  • Failure to provide error handling and consider edge cases  

Candidates are evaluated majorly on their understanding of core JavaScript concepts and skills. By mastering the fundamentals and practicing, candidates can crack their interview. Also, it’s important to focus on being clear, accurate , and honest in the interview.  

Related Interview Questions

  • Java programming interview questions and Answers
  • Top 40 Java Interview Questions and Answers 2023

Related Job Descriptions

  • Java Developer Job Description
  • Full Stack Developer Job Description Template

By clicking “Accept", you consent to our website's use of cookies to give you the most relevant experience by remembering your preferences and repeat visits. You may visit "cookie policy” to know more about cookies we use.

JavaScript Coding Interview Practice – Sample Interview Questions and Solutions

David Goggins is an ultramarathon runner, a public speaker, a retired navy SEAL, and the author of the book ' Can't Hurt Me: Master Your Mind and Defy the Odds '. He's one of my role models because of his physical strength and mental resilience.

You might say: "Wait a second! We get it. This person is obviously the epitome of success. But he has non-technical skills. So why is he relevant to JavaScript coding interviews?"

Well, if you're ready, let's explore this together.

Rocky Balboa As a Mentor

In response to a question, David says, 'The Rocky Movie changed my life." In that pep talk , he refers to this scene (min 1.30-1.42) where the fictional character, Rocky - despite being beaten up badly by his opponent in the final boxing round - refuses to give up no matter what.

David describes that particular moment as the time when Rocky - initially depicted as an underdog by the screenwriter - overcomes all the odds and strikes awe in his rival.

image-280

Let's admit it. Being a good programmer is not that easy. And especially if you are at the beginning of your career, technical job interviews can be seriously daunting. In short, it might be nice to reach David's (and Rocky's) mindset.

With that kind of drive and confidence, you're much less likely to consider giving up regardless of the types of challenges you face in your wonderful yet difficult journey of getting a developer job.

Why Coding Interviews Are Difficult

During coding interviews, you are expected to fix coding problems with some theoretical knowledge. But the caveat is you must do that in real time, which sometimes scares new developers off.

There are several types of coding interviews. But the most challenging one is probably a whiteboard interview. In these types of interviews, you have to code in front of a future employer / a senior software developer.

image-319

These interviews can be extra stressful because you are typically not allowed to have a computer to google any unknown concepts or to get some code snippets from the internet. You are only given a marker to solve the question on a whiteboard as the name suggests.

Do Interviews Reflect What You'll Do in Your Job?

Not necessarily. So why are they holding these scary coding interviews? Well, the reason is to test your problem solving skills in general. At times, finding the correct answer may not even be that important.

What matters is how you reach that conclusion / solution and which algorithms you prefer to use along the way. In other words, your ability to function well under stress is being tested by tech companies.

image-329

Let's face it. You'll come across lots of stressful situations in your future job, and how you deal with certain issues is especially crucial. Therefore, your future employer naturally wants to witness firsthand whether you are the right fit for the job.

What is the Purpose of This Tutorial?

In this post, I'll walk you through some popular JavaScript interview concepts through examples. I'll also do my best to show you what recruiters / interviewers might actually be looking for in a candidate while they code in front of them.

To simply put, we'll examine some models and try to solve the related puzzles together.

By the end of this tutorial, you'll hopefully have an idea about a number of important array methods. But most importantly, you'll unlock how to approach some coding challenges in the best way possible.

What Exactly is the Memory Palace Method?

Before we start, just be aware that in the sample data down below, I've used some late celebrities' names intentionally so that all those details can be catchy in the long run.

An ancient technique called the Memory Palace clearly says that the weirder the details, the easier it is to remember them – and a made-up story / creating context is even more effective.

If you try to visualise the related situation vividly and associate the given programming concepts with some bizarre details in your mind, you might feel less stressed and confused when you see a similar problem next time. This is because it might be easier for you to create specific links and as such remember things easily. This is how our brains work.

Well, even the fictional figure ' Sherlock Holmes ', the smartest guy on the planet, benefits from this method when solving complicated crimes – so why shouldn't we?

image-321

How to Approach Coding Problems

In our imaginary interview, you'll see that four extraordinary musicians from the past are listed as passengers on a flight. We have their food choices and the number of connecting flights they need to take after their incredible performances on stage in different parts of the world.

Let's say just for the sake of argument our phenomenal figures (Freddie Mercury, Amy Winehouse, Kurt Cobain, and Michael Jackson) are about to fly from different destinations to Los Angeles just to be able to dine out together at a swanky restaurant, as they enjoy each other's company so much.

After all, this is our own private memory palace, so we can absolutely do whatever we want to do in our minds. Remember unusual details will stick better. That's why I'm trying to add more to spice things up.

This method explicitly suggests describing every single detail with some vivid adjectives so that you can associate them with the things you plan to learn in the long run.

Scientists say short term memory and long term memory function very differently. To put it simply, we need a way to put all those core concepts (not necessarily the syntax) about programming in our long term memory. That's why it can be nice to benefit from the memory palace method in our journey.

image-326

Plus, I feel like you get to picture this unusual scenario with a smile on your face. Well, wouldn't it be great if these awesome souls could have seen that they are now helping us / the programming community as the guests of a freeCodeCamp article?

Sample Interview Questions

Let's get back to the real life now though. Remember you're still in the interview and as you see below, three questions in a row are waiting for you.

To solve the puzzles, you're expected to use the data inside the following array of objects in practical ways.

You'll certainly need to come up with the right algorithms and try to find the most effective solution that can satisfy the interviewer.

The above questions are in fact not that hard. But, how we'll handle them is a great opportunity to compare alternative solutions for a single problem. At the end of the day, quality is what counts for recruiters / interviewers.

Interview Question 1: How to Get Passengers' Names

Let's get the passengers' names as requested. The first solution is through a 'for loop' method. So we first need to use an empty array to push the passengers' names right inside it at the end of the loop.

Below, [i] represents the current passenger and we simply loop through the 'passengers' array to access the names of the passengers. Then, we need to lock them up in our empty array / passengerNames.

image-331

Alright, we solved the puzzle, but is it enough? Or might the interviewers expect you to come up with a better solution?

Alternative Solution #1:

We can reach the desired result by using the ' forEach ' function as well. This solution is even a bit better than the previous one because there is no index expression in this one.

image-332

To benefit from 'forEach', we need a callback function . With this arrangement, we are able to reach every passenger in the list. However, just like in the previous solution, we first need an empty array to push the items / passengers' names.

Even though the result is the same, this piece of code is shorter. Writing neater codes is what is – in fact – expected from you.

In other words, not only the solution matters, but also how you reach it is being evaluated by the recruiters. For this reason, it is a good idea to plan your action rather than writing the first idea in your mind on the whiteboard.

Alternative Solution 2:

Here comes the best solution. We can also utilise the ' map ' function to tackle the same problem. Let's see how.

image-333

The map function also loops through the array and returns a new array for every item in the list. With this set-up, we simply return a single element, not an object.

The result will again be the same in the console, but your code will even be better than the first and second one because this time, we don't need to create an empty array before the actual task.

Here is the food for thought on this topic. Those who say 'less is more' have a point when it comes to writing codes.

Interview Question 2: How to Get Vegetarian/Vegan Singers

Let's now take a look at the next challenge. The new task asks us to obtain only the vegetarian / vegan singers from the passengers' list by also keeping the first argument in the main question section.

How to Solve With a 'For Loop'

Again, we can use the same old 'for loop' for this one as well. All we need to do is to check whether there are any vegetarian / vegan singers in our passenger list through an 'if' statement inside our existing function.

image-334

We do that with the isVegetarianOrVegan property in our object. Basically, what we say is this: if the relevant statement is true (if there are any vegan / vegetarian passengers in the list), just push those items into our new array. The result will give us three singers' names as those are listed as  'vegetarian or vegan' in the data part.

How to Solve with 'forEach'

As a matter of fact, the 'forEach' function handles the problem similarly. But once again, it has too many lines of codes as you see below, so it isn't the ideal version.

image-335

How to Solve with 'Filter' & 'Map'

To come up with the best option, this time, we will use two different methods. The ' filter ' and the 'map' functions will – in a way – collaborate to create better logic when solving the given problem. Let's examine the following code snippet closely now.

image-336

With the filter method, we only get the vegetarian / vegan passengers from our array in the first place. If it finds some non-vegetarian / vegan passengers (like our beloved 'Freddie'), it will get rid of them automatically.

Briefly, the first part of the equation, the 'filter' method will simply work through 'yes' or 'no' model.

Then, the 'map' function will come in, eventually giving us a brand new array showing the vegetarian / vegan passengers only.

This final solution will prove your future employer that you genuinely know what you're doing and you are really taking the right steps to be a hotshot developer.

Interview Question #3: How to Sort Passengers by Connecting Flights

The last section asks us to sort the list of our super cool passengers by the number of the connecting flights they'll take to eventually reach LA. Let's see who has more and as such, will be pretty exhausted.

Spoiler alert! Amy with four connecting flights in total might be a bit sleepy in the get-together at that fancy restaurant. But there is no doubt that she will somehow rock where ever she goes.

image-322

Anyway, what we need for this task is to know how the ' sort ' function operates.

Primarily, it compares items one by one and returns something as a result. In our case, it will be the number of connected flights. But how does it make that comparison? What is the logic behind that?

image-343

The above lines of code are pretty clear in general. Thanks to the 'sort' function, we list those months in alphabetical order.

Well, here comes the big question. How does the code / system know that 'a' is the first letter of the alphabet and as such, the list starts with the 'd' letter (December)?

The reason is that the 'sort function' lists things in ascending order by default. But can't we change this setting? Perhaps, we need to list items in descending order. Of course, we can.

Let's see how. To achieve what we want, we may utilise 'a' and 'b' letters as parameters leading to different directions.

image-338

Simultaneously, we can benefit from the assistance of three numbers: -1,+1, 0 as seen above. When sorting items in descending or ascending order or finding the equal values, they can be quite handy.

Tricky Bit of the 'Sort' Function

In the following example, the list is sorted in ascending order. Why is it like that? Here is the reason. When we return those 'a' and 'b' parameters, we use this order:  'a - b' . That gives us ascending values by default.

image-339

However, if we swap them and say 'b - a', the list will be seen in descending order this time. That's the tricky bit when it comes to the 'sort' function.

In the above example, the first version (regular function) and the second one (arrow function) are in essence the same, but just be aware that arrow functions came with ES6 .

Although arrow functions help developers to write less code, you cannot use them everywhere. (Read this to find out when to use them.)

Testing Our New Knowledge

Shall we now analyse the situation of our passengers through our new perspective? We know that the last task asks us to sort the number of flights in descending order. But the following set-up does the opposite.

It can only give us the list in ascending order. Why? It's simply because of the pre-defined order (passenger1.connectedFlights - passenger2.connectedFlights) as in the case of a - b example.

Once we swap the order (passenger2.connectedFlights - passenger1.connectedFlights) as you see in the following code snippet, our problem will be solved and the list will come in descending order.

image-342

Can We Also Use 'for loop' or 'forEach'?

Well, yes and no. Both would be low-level solutions for this question.

We should keep in mind that the sort function mutates an array. This is a kind of side effect which changes the original array and that might be a problem if we use 'for loop' or 'forEach' as a solution.

There are of course ways to avoid mutation in the sort function, but in our example, it will lead to more lines of codes, which is not practical at all.

Wrapping Up

We've started the article with David Goggins, the symbol of resilience and grit, so let's end it with his inspiring presence and ideas.

If you happen to read this modern day hero's book or listen to one of those famous podcast episodes (For example, this one ) where he was a guest speaker, you'll immediately understand that he wasn't born that way. Rather, his secret lies in the fact that he never gives up, against all odds.

Coding interviews are tough, but if you keep going after your goals by visualising the scene of success in your mind over and over again, it will -  sooner or later - be yours.

image-328

Many thanks for reading this post. If you've liked this article, one of the best ways to support me is to share it. Should you have any questions or comments, you can always contact me via LinkedIn . I'll be more than happy to help you out with your queries.

Happy coding!

“Knowledge is power.” – Francis Bacon

Software Developer || UI Designer || Technical Writer

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Cheat Sheet
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JS Web Technology

Related Articles

  • Solve Coding Problems

HTML Interview Questions

  • HTML Interview Questions and Answers (2024)
  • HTML Interview Questions and Answers (2024) - Intermediate Level
  • HTML Interview Questions and Answers (2024) – Advanced Level

CSS Interview Questions

  • CSS Interview Questions and Answers

JavaScript Interview Questions

Javascript interview questions and answers.

  • JavaScript Interview Questions and Answers (2024) - Intermediate Level
  • JavaScript Interview Questions and Answers (2024) - Advanced Level

TypeScript Interview Questions

  • TypeScript Interview Questions and Answers (2024)

jQuery Interview Questions

  • jQuery Interview Questions and Answers (2024)
  • jQuery Interview Questions and Answers | Set-2
  • jQuery Interview Questions and Answers | Set-3

Angular Interview Questions

  • AngularJS Interview Questions and Answers (2024)

React Interview Questions

  • React Interview Questions and Answers
  • React Interview Questions and Answers (2024) - Intermediate Level
  • React Interview Question and Answers (2024) - Advance Level

Node Interview Questions

  • Node.js Interview Questions and Answers
  • Node Interview Questions and Answers (2024) - Intermediate Level
  • Node Interview Questions and Answers (2024) - Advanced Level

MERN Interview Questions

  • Top MERN Stack Interview Questions

PHP Interview Questions

  • PHP Interview Questions and Answers (2024)
  • PHP Interview Questions and Answers (2024) | Set-2

Tailwind CSS Interview Questions

  • Tailwind CSS Interview Questions and Answers

Frontend Developer Interview Questions

  • Front End Developer Interview Questions and Answers [2024]

JavaScript (JS) is the most popular lightweight scripting and compiled programming language. It was developed by Brendan Eich in 1995 . It is well-known as a scripting language for web pages, mobile apps, web servers, and many more.

In this article, we will provide 60+ JavaScript interview questions and answers tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience. Here, we cover everything, including Core JavaScript Concepts , ES6+ features, DOM manipulation, asynchronous JavaScript, error handling, JavaScript frameworks and libraries, and more, that will surely help you to crack your next JavaScript interview.

JavaScript Interview Questions and Answers

JavaScript Interview Questions and Answers (2024)

Before proceeding to learn JavaScript interview questions and answers , first we learn the complete JavaScript Tutorial .

Table of Content

JavaScript Interview Questions for Freshers

Javascript intermediate interview questions, javascript interview questions for experienced.

Let’s discuss some common questions that you should prepare for the interviews. These questions will be helpful in clearing the interviews specially for the frontend development role.

1. What are the differences between Java and JavaScript?  

JavaScript is a client-side scripting language and Java is object Oriented Programming language. Both of them are totally different from each other.

  • JavaScript : It is a light-weighted programming language (“scripting language”) for developing interactive web pages. It can insert dynamic text into the HTML elements. JavaScript is also known as the browser’s language.
  • Java : Java is one of the most popular programming languages. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”.

2. What are JavaScript Data Types?  

There are three major Data types in JavaScript.

3. Which symbol is used for comments in JavaScript?  

Comments prevent the execution of statements. Comments are ignored while the compiler executes the code. There are two type of symbols to represent comments in JavaScript:

  • Double slash: It is known as a single-line comment.
  • Slash with Asterisk: It is known as a multi-line comment.

4. What would be the result of 3+2+”7″?

 Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2 will be 5. Then the output will be 5+”7″ = 57.

5. What is the use of the isNaN function?

 The number isNan function determines whether the passed value is NaN (Not a number) and is of the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number, else it returns false.

6. Which is faster in JavaScript and ASP script?

  JavaScript is faster compared to ASP Script. JavaScript is a client-side scripting language and does not depend on the server to execute. The ASP script is a server-side scripting language always dependable on the server.

7. What is negative infinity?

 The negative infinity is a constant value represents the lowest available value. It means that no other number is lesser than this value. It can be generate using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity.

8. Is it possible to break JavaScript Code into several lines?

 Yes, it is possible to break the JavaScript code into several lines in a string statement. It can be broken by using the backslash ‘\’ .  For example:

The code-breaking line is avoid by JavaScript which is not preferable.

9. Which company developed JavaScript?

Netscape developed JavaScript and was created by Brenden Eich in the year of 1995.

10. What are undeclared and undefined variables?

  • Undefined : It occurs when a variable is declare not not assign any value. Undefined is not a keyword.
  • Undeclared : It occurs when we try to access any variable which is not initialize or declare earlier using the var or const keyword. If we use ‘typeof’ operator to get the value of an undeclare variable, we will face the runtime error with the return value as “undefined”. The scope of the undeclare variables is always global.

11. Write a JavaScript code for adding new elements dynamically.  

12. what are global variables how are these variables declared, and what are the problems associated with them.

 In contrast, global variables are the variables that define outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters. 

It is difficult to debug and test the code that relies on global variables.

13. What do you mean by NULL in JavaScript?

 The NULL value represents that no value or no object. It is known as empty value/object.

14. How to delete property-specific values?

  The delete keyword deletes the whole property and all the values at once like

15. What is a prompt box?

 The prompt box is a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null.

16. What is the ‘this’ keyword in JavaScript?

 Functions in JavaScript are essential objects. Like objects, it can be assign to variables, pass to other functions, and return from functions. And much like objects, they have their own properties. ‘this’ stores the current execution context of the JavaScript program. Thus, when it use inside a function, the value of ‘this’ will change depending on how the function is defined, how it is invoked, and the default execution context.

17. Explain the working of timers in JavaScript. Also elucidate the drawbacks of using the timer, if any.

The timer executes some specific code at a specific time or any small amount of code in repetition to do that you need to use the functions setTimout , setInterval, and clearInterval . If the JavaScript code sets the timer to 2 minutes and when the times are up then the page displays an alert message “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

18. What is the difference between ViewState and SessionState?

  • ViewState: It is specific to a single page in a session.
  • SessionState: It is user specific that can access all the data on the web pages.

19. How to submit a form using JavaScript?

You can use document.form[0].submit() method to submit the form in JavaScript.

20. Does JavaScript support automatic type conversion?  

Yes, JavaScript supports automatic type conversion.

21. What are all the looping structures in JavaScript ?

  • while loop :  A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
  • for loop :  A for loop provides a concise way of writing the loop structure. Unlike a while loop, for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
  • do while :  A do-while loop is similar to while loop with the only difference that it checks the condition after executing the statements, and therefore is an example of Exit Control Loop.

22. How can the style/class of an element be changed?

To change the style/class of an element there are two possible ways. We use  document.getElementByID method

23. Explain how to read and write a file using JavaScript?

  • The  readFile()  functions is used for reading operation.
  • The  writeFile()  functions is used for writing operation.

24. What is called Variable typing in JavaScript ?

The  variable typing  is the type of variable used to store a number and using that same variable to assign a “string”.

25. How to convert the string of any base to integer in JavaScript?

In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function. The parseInt() function returns Nan (not a number) when the string doesn’t contain number.

26. Explain how to detect the operating system on the client machine?

To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is a read-only property and it returns the string that represents the version information of the browser.

27. What are the types of Pop up boxes available in JavaScript?

There are three types of pop boxes available in JavaScript.

28. What is the difference between an alert box and a confirmation box?

An alert box will display only one button which is the OK button. It is used to inform the user about the agreement has to agree. But a Confirmation box displays two buttons OK and cancel, where the user can decide to agree or not.

29. What is the disadvantage of using innerHTML in JavaScript?

There are lots of disadvantages of using the innerHTML in JavaScript as the content will replace everywhere. If you use += like “innerHTML = innerHTML + ‘html’” still the old content is replaced by HTML. It preserves event handlers attached to any DOM elements.

30. What is the use of void(0) ?

The void(0) is used to call another method without refreshing the page during the calling time parameter “zero” will be passed.

For further reading, check out our dedicated article on Intermediate Javascript Interview Questions . Inside, you’ll discover over 20 questions with detailed answers.

31.  What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program or a function in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict” instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.

32.  How to get the status of a CheckBox?

The DOM Input Checkbox Property is used to set or return the checked status of a checkbox field. This property is used to reflect the HTML Checked attribute.

If the CheckBox is checked then it returns True.

33.  How to explain closures in JavaScript and when to use it?

The closure is created when a child functions to keep the environment of the parent’s scope even after the parent’s function has already executed. The Closure is a locally declared variable related to a function. The closure will provide better control over the code when using them.

34.  What is the difference between call() and apply() methods ?

Both methods are used in a different situation

  • call() Method:  It calls the method, taking the owner object as argument. The keyword this refers to the ‘owner’ of the function or the object it belongs to. We can call a method that can be used on different objects.
  • apply() Method:  The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array.

35.  How to target a particular frame from a hyperlink in JavaScript ?

This can be done by using the  target  attribute in the hyperlink. Like

36.  Write the errors shown in JavaScript?

There are three different types of errors in JavaScript.

  • Syntax error:  A syntax error is an error in the syntax of a sequence of characters or tokens that are intended to be written in a particular programming language.
  • Logical error:  It is the most difficult error to be traced as it is the error on the logical part of the coding or logical error is a bug in a program that causes to operate incorrectly and terminate abnormally.
  • Runtime Error:  A runtime error is an error that occurs during the running of the program, also known as an exception.

37.  What is the difference between JavaScript and Jscript?

  • It is a scripting language developed by Netscape.
  • It is used to design client and server-side applications.
  • It is completely independent of Java language.
  • It is a scripting language developed by Microsoft.
  • It is used to design active online content for the word wide Web.

38.  What does   var myArray = [[]];  statement declares? 

In JavaScript, this statement is used to declare a two-dimensional array.

39. How many ways an HTML element can be accessed in JavaScript code? 

There are four possible ways to access HTML elements in JavaScript which are:

  • getElementById() Method:  It is used to get the element by its id name.
  • getElementsByClass() Method:  It is used to get all the elements that have the given classname.
  • getElementsByTagName() Method:  It is used to get all the elements that have the given tag name.
  • querySelector() Method:  This function takes CSS style selector and returns the first selected element.

40. What is the difference between innerHTML & innerText? 

The innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property sets or returns the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automatically encode and decode text.

41. What is an event bubbling in JavaScript?

Consider a situation an element is present inside another element and both of them handle an event. When an event occurs in bubbling, the innermost element handles the event first, then the outer, and so on.

For further reading, check out our dedicated article on Advanced Javascript Interview Questions . Inside, you’ll discover 20+ questions with detailed answers.

Please Login to comment...

  • interview-preparation
  • JavaScript-Interview-Questions
  • JavaScript-Questions
  • Web Technologies
  • Dharmendra_Kumar
  • shobhit_sharma
  • vishalkumar2204
  • shubhamkquv4
  • souravkum5y3
  • 10 Best Notion Integrations to Connect Your Apps
  • 10 ChatGPT Prompts for Financial Analysts to Streamline Analysis
  • 10 Best AI Tools for Solving Math Problems Effortlessly [Free + Paid]
  • Elicit vs. Scholarcy: Which AI Extracts Better Research Insights?
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Free Javascript challenges

Learn Javascript online by solving coding exercises.

Javascript for all levels

Solve Javascript tasks from beginner to advanced levels.

Accross various subjects

Select your topic of interest and start practicing.

Start your learning path here

Why jschallenger, a hands-on javascript experience.

JSchallenger provides a variety of JavaScript exercises, including coding tasks, coding challenges, lessons, and quizzes.

Structured learning path

JSchallenger provides a structured learning path that gradually increases in complexity. Build your skills and knowledge at your own pace.

Build a learning streak

JSchallenger saves your learning progress. This feature helps to stay motivated and makes it easy for you to pick up where you left off.

Type and execute code yourself

Type real JavaScript and see the output of your code. JSchallenger provides syntax highlighting for easy understanding.

Join 1.000s of users around the world

Most popular challenges, most failed challenges, what users say about jschallenger.

Photography of Mohamed Ibrahim who describes JSchallenger as a very helpful free resource for Javascript exercises

Mohamed Ibrahim

Photography of Tobin Shields who sais that JSchallenger is a great tool with Javascript beginner exercises

Tobin Shields

Photography of Meet Patel who describes JSchallenger as a great place to solve Javascript problems

37 Essential JavaScript Interview Questions  *

Toptal sourced essential questions that the best javascript developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..

javascript problem solving questions and answers

Interview Questions

What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?

Although typeof bar === "object" is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!

Therefore, the following code will, to the surprise of most developers, log true (not false ) to the console:

As long as one is aware of this, the problem can easily be avoided by also checking if bar is null :

To be entirely thorough in our answer, there are two other things worth noting:

First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:

Second, the above solution will return true if bar is an array (e.g., if var bar = []; ). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:

However, there’s one other alternative that returns false for nulls, arrays, and functions, but true for objects:

Or, if you’re using jQuery:

ES5 makes the array case quite simple, including its own null check:

What will the code below output to the console and why?

Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.

However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:

But in fact, var a = b = 3; is actually shorthand for:

As a result (if you are not using strict mode), the output of the code snippet would be:

But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b; , b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.

Note that, in strict mode (i.e., with use strict ), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined , thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)

The above code will output the following to the console:

In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo .

In the inner function, though, this no longer refers to myObject . As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance JavaScript Developer Jobs

What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?

This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.

Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict() . If this has been done, your code can still use $ employing this closure technique, as follows:

What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?

The short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.

Some of the key benefits of strict mode include:

  • Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.
  • Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.
  • Eliminates this coercion . Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.
  • Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g. var object = {foo: "bar", foo: "baz"}; ) but as of ECMAScript 2015 this is no longer the case.
  • Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems).
  • Throws error on invalid usage of delete . The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.

Consider the two functions below. Will they both return the same thing? Why or why not?

Surprisingly, these two functions will not return the same thing. Rather:

will yield:

Not only is this surprising, but what makes this particularly gnarly is that foo2() returns undefined without any error being thrown.

The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2() , a semicolon is automatically inserted immediately after the return statement.

No error is thrown since the remainder of the code is perfectly valid, even though it doesn’t ever get invoked or do anything (it is simply an unused code block that defines a property bar which is equal to the string "hello" ).

This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.

What will the code below output? Explain your answer.

An educated answer to this question would simply be: “You can’t be sure. it might print out 0.3 and true , or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.”

The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:

A typical solution is to compare the absolute difference between two numbers with the special constant Number.EPSILON :

In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?

The values will be logged in the following order:

Let’s first explain the parts of this that are presumably more obvious:

1 and 4 are displayed first since they are logged by simple calls to console.log() without any delay

2 is displayed after 3 because 2 is being logged after a delay of 1000 msecs (i.e., 1 second) whereas 3 is being logged after a delay of 0 msecs.

OK, fine. But if 3 is being logged after a delay of 0 msecs, doesn’t that mean that it is being logged right away? And, if so, shouldn’t it be logged before 4 , since 4 is being logged by a later line of code?

The answer has to do with properly understanding JavaScript events and timing .

The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload event) while the browser is busy (e.g., processing an onclick ), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload script is executed).

Similarly, setTimeout() also puts execution of its referenced function into the event queue if the browser is busy.

When a value of zero is passed as the second argument to setTimeout() , it attempts to execute the specified function “as soon as possible”. Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That’s why in the above example, the call to console.log(4) occurs before the call to console.log(3) (since the call to console.log(3) is invoked via setTimeout, so it is slightly delayed).

Write a simple function (less than 160 characters) that returns a boolean indicating whether or not a string is a palindrome .

The following one line function will return true if str is a palindrome; otherwise, it returns false.

For example:

Write a sum method which will work properly when invoked using either syntax below.

There are (at least) two ways to do this:

In JavaScript, functions provide access to an arguments object which provides access to the actual arguments passed to a function. This enables us to use the length property to determine at runtime the number of arguments passed to the function.

If two arguments are passed, we simply add them together and return.

Otherwise, we assume it was called in the form sum(2)(3) , so we return an anonymous function that adds together the argument passed to sum() (in this case 2) and the argument passed to the anonymous function (in this case 3).

When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored. On the other hand, if the number of arguments passed is less than the number of arguments in the function definition, the missing arguments will have a value of undefined when referenced within the function. So, in the above example, by simply checking if the 2nd argument is undefined, we can determine which way the function was invoked and proceed accordingly.

Consider the following code snippet:

(a) What gets logged to the console when the user clicks on “Button 4” and why?

(b) Provide one or more alternate implementations that will work as expected.

(a) No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point that the onclick method is invoked (for any of the buttons), the for loop has already completed and the variable i already has a value of 5. (Bonus points for the interviewee if they know enough to talk about how execution contexts, variable objects, activation objects, and the internal “scope” property contribute to the closure behavior.)

(b) The key to making this work is to capture the value of i at each pass through the for loop by passing it into a newly created function object. Here are four possible ways to accomplish this:

Alternatively, you could wrap the entire call to btn.addEventListener in the new anonymous function:

Or, we could replace the for loop with a call to the array object’s native forEach method:

Lastly, the simplest solution, if you’re in an ES6/ES2015 context, is to use let i instead of var i :

Assuming d is an “empty” object in scope, say:

…what is accomplished using the following code?

The snippet of code shown above sets two properties on the object d . Ideally, any lookup performed on a JavaScript object with an unset key evaluates to undefined . But running this code marks those properties as “own properties” of the object.

This is a useful strategy for ensuring that an object has a given set of properties. Passing this object to Object.keys will return an array with those set keys as well (even if their values are undefined ).

The logged output will be:

arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e','s'] ] ) after the above code is executed for the following reasons:

Calling an array object’s reverse() method doesn’t only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1 ).

The reverse() method returns a reference to the array itself (i.e., in this case, arr1 ). As a result, arr2 is simply a reference to (rather than a copy of) arr1 . Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3); ), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.

And a couple of side points here that can sometimes trip someone up in answering this question:

Passing an array to the push() method of another array pushes that entire array as a single element onto the end of the array. As a result, the statement arr2.push(arr3); adds arr3 in its entirety as a single element to the end of arr2 (i.e., it does not concatenate the two arrays, that’s what the concat() method is for).

Like Python, JavaScript honors negative subscripts in calls to array methods like slice() as a way of referencing elements at the end of the array; e.g., a subscript of -1 indicates the last element in the array, and so on.

What will the code below output to the console and why ?

Here’s why…

The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.

Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2" . Since one of the operands ( "2" ) is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1" , 1 + "2" yields "12" . Then, "12" + "2" yields "122" .

Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2" (the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3 . But then, we have an operation between a number and a string (i.e., 3 and "2" ), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32" .

Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than + . So "1" becomes 1 , which then becomes -1 when the - is applied, which is then added to 1 yielding 0 , which is then converted to a string and concatenated with the final "2" operand, yielding "02" .

Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112" .

Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield “NaN2”.

Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN . But any operator applied to NaN with any other numeric operand will still yield NaN .

The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?

The potential stack overflow can be avoided by modifying the nextListItem function as follows:

The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function ( nextListItem ) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem . Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.

What is a “closure” in JavaScript? Provide an example.

A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function’s scope, and (3) global variables.

Here is an example:

In the above example, variables from innerFunc , outerFunc , and the global namespace are all in scope in the innerFunc . The above code will therefore produce the following output:

What would the following lines of code output to the console?

Explain your answer.

The code will output the following four lines:

In JavaScript, both || and && are logical operators that return the first fully-determined “logical value” when evaluated from left to right.

The or ( || ) operator. In an expression of the form X||Y , X is first evaluated and interpreted as a boolean value. If this boolean value is true , then true (1) is returned and Y is not evaluated, since the “or” condition has already been satisfied. If this boolean value is “false”, though, we still don’t know if X||Y is true or false until we evaluate Y , and interpret it as a boolean value as well.

Accordingly, 0 || 1 evaluates to true (1), as does 1 || 2 .

The and ( && ) operator. In an expression of the form X&&Y , X is first evaluated and interpreted as a boolean value. If this boolean value is false , then false (0) is returned and Y is not evaluated, since the “and” condition has already failed. If this boolean value is “true”, though, we still don’t know if X&&Y is true or false until we evaluate Y , and interpret it as a boolean value as well.

However, the interesting thing with the && operator is that when an expression is evaluated as “true”, then the expression itself is returned. This is fine, since it counts as “true” in logical expressions, but also can be used to return that value when you care to do so. This explains why, somewhat surprisingly, 1 && 2 returns 2 (whereas you might it expect it to return true or 1 ).

What will be the output when the following code is executed? Explain.

The code will output:

In JavaScript, there are two sets of equality operators. The triple-equal operator === behaves like any traditional equality operator would: evaluates to true if the two expressions on either of its sides have the same type and the same value. The double-equal operator, however, tries to coerce the values before comparing them. It is therefore generally good practice to use the === rather than == . The same holds true for !== vs != .

What is the output out of the following code? Explain your answer.

The output of this code will be 456 ( not 123 ).

The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]" . As a result, a[b] and a[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b] .

What will the following code output to the console:

The code will output the value of 10 factorial (i.e., 10!, or 3,628,800).

Here’s why:

The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1 . Here, therefore, is what this does:

Consider the code snippet below. What will the console output be and why?

The output will be 1 , even though the value of x is never set in the inner function. Here’s why:

As explained in our JavaScript Hiring Guide , a closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an “inner function”; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function’s variables.

Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x , which is found to have a value of 1 .

What will the following code output to the console and why:

What is the issue with this code and how can it be fixed.

The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist.

One way to fix the stoleSecretIdentity() function is as follows:

Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents ( not just its immediate children ). For each element visited, the function should pass that element to a provided callback function.

The arguments to the function should be:

  • a DOM element
  • a callback function (that takes a DOM element as its argument)

Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here’s an example solution:

Testing your this knowledge in JavaScript: What is the output of the following code?

Why isn’t it 10 and 5 ?

In the first place, as fn is passed as a parameter to the function method , the scope ( this ) of the function fn is window . var length = 10; is declared at the window level. It also can be accessed as window.length or length or this.length (when this === window .)

method is bound to Object obj , and obj.method is called with parameters fn and 1 . Though method is accepting only one parameter, while invoking it has passed two parameters; the first is a function callback and other is just a number.

When fn() is called inside method , which was passed the function as a parameter at the global level, this.length will have access to var length = 10 (declared globally) not length = 5 as defined in Object obj .

Now, we know that we can access any number of arguments in a JavaScript function using the arguments[] array.

Hence arguments[0]() is nothing but calling fn() . Inside fn now, the scope of this function becomes the arguments array, and logging the length of arguments[] will return 2 .

Hence the output will be as above.

Consider the following code. What will the output be, and why?

var statements are hoisted (without their value initialization) to the top of the global or function scope it belongs to, even when it’s inside a with or catch block. However, the error’s identifier is only visible inside the catch block. It is equivalent to:

What will be the output of this code?

Neither 21, nor 20, the result is undefined

It’s because JavaScript initialization is not hoisted.

(Why doesn’t it show the global value of 21? The reason is that when the function is executed, it checks that there’s a local x variable present but doesn’t yet declare it, so it won’t look for global one.)

What will this code print?

It will print 0 1 2 3 4 , because we use let instead of var here. The variable i is only seen in the for loop’s block scope.

What do the following lines output, and why?

The first statement returns true which is as expected.

The second returns false because of how the engine works regarding operator associativity for < and > . It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1 . true has value 1 , so it then compares 1 > 1 , which is false .

How do you add an element at the begining of an array? How do you add one at the end?

With ES6, one can use the spread operator:

Or, in short:

Imagine you have this code:

a) Will this result in a crash?

b) What will this output?

a) It will not crash. The JavaScript engine will make array slots 3 through 9 be “empty slots.”

b) Here, a[6] will output undefined , but the slot still remains empty rather than filled with undefined . This may be an important nuance in some cases. For example, when using map() , empty slots will remain empty in map() ’s output, but undefined slots will be remapped using the function passed to it:

What is the value of typeof undefined == typeof NULL ?

The expression will be evaluated to true, since NULL will be treated as any other undefined variable.

Note: JavaScript is case-sensitive and here we are using NULL instead of null .

What would following code return?

typeof 1 will return "number" and typeof "number" will return string .

What will be the output of the following code:

Explain your answer. How could the use of closures help here?

The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5.

The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i , which was 5.

Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows:

This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.

In an ES2015 context , you can simply use let instead of var in the original code:

What is NaN ? What is its type? How can you reliably test if a value is equal to NaN ?

The NaN property represents a value that is “not a number”. This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4 ), or because the result of the operation is non-numeric.

While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them.

For one thing, although NaN means “not a number”, its type is, believe it or not, Number :

Additionally, NaN compared to anything – even itself! – is false:

A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN() , but even using isNaN() is an imperfect solution .

A better solution would either be to use value !== value , which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.

What will the following code output and why?

Output to the console will be “3”.

There are three closures in the example, each with it’s own var b declaration. When a variable is invoked closures will be checked in order from local to global until an instance is found. Since the inner closure has a b variable of its own, that is what will be output.

Furthermore, due to hoisting the code in inner will be interpreted as follows:

Discuss possible ways to write a function isInteger(x) that determines if x is an integer.

This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger() method is provided.

The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.

With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following use of the bitwise XOR operator:

The following solution would also work, although not as elegant as the one above:

The following function (or with Math.ceil() or Math.floor() in place of Math.round() ) might also seem useful, but the results are not exactly the same as with the above two functions:

The difference is, these Math -based solutions return true for Infinity and -Infinity , whereas the others (and notably ES6’s Number.isInteger() ) return false .

Another fairly common incorrect solution is the following:

While this parseInt -based approach will work well for many values of x , once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21 ). Accordingly, parseInt() will then try to parse 1e+21 , but will stop parsing when it reaches the e character and will therefore return a value of 1 . Observe:

How do you clone an object?

Now the value of objclone is {a: 1 ,b: 2} but points to a different object than obj .

Note the potential pitfall, though: Object.assign() will just do a shallow copy, not a deep copy. This means that nested objects aren’t copied. They still refer to the same nested objects as the original:

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of JavaScript Developers

Looking to land a job as a JavaScript Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for JavaScript Developers?

Looking for JavaScript Developers ? Check out Toptal’s JavaScript developers.

Jay Johnston, Freelance JavaScript Developer for Hire.

Jay Johnston

Coding HTML, CSS, and JavaScript since his armed forces days in 1997, Jay enjoys bringing value to clients via eCommerce solutions, legacy integrations, and optimized PHP and JavaScript-driven applications. His preferred DevOps environment is AWS, where he has strong skills in (and not limited to): Relational Database Services (RDS), Redshift, Dynamo DB, Data Migration Services (DMS), Lambda (serverless and microservices), Cloudwatch, Cloudtrail, and Event Bridge.

Tyler Standley, Freelance JavaScript Programmer for Hire.

Tyler Standley

Along with strong communication skills and an exemplary work ethic, Tyler brings his hands-on experience with a wide range of programming languages. Recently, though, his focus has been directed towards JavaScript libraries. Throughout his career, he’s worked on multiple agile teams as a core developer and is now interested in working on anything JavaScript-related.

Justin Michela, JavaScript Coder.

Justin Michela

Justin is a technical professional with a passion for learning and 18+ years of experience leading teams to build enterprise-grade distributed applications that solve real-world problems. Justin firmly believes that collaboration across all facets of a business, from development to marketing to sales, is required to succeed in this endeavor.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

30 JavaScript Coding Interview Questions for Beginner, Mid-Level and Expert Developers

javascript coding interview questions

JavaScript is a leading programming language for creating interactive and dynamic web pages. You will see a lot of popular frameworks and libraries based on JavaScript, such as jQuery, VueJS, ReactJS, AngularJS and others. It is no surprise that JavaScript is the main programming language for the front-end development of software applications. 

Today we will guide you on how to design coding challenges for evaluating JavaScript developers. We will suggest coding challenges for beginner, mid-level and expert JavaScript developers. Let’s start with coding challenges that are suitable for beginner-level developers.

Interview Questions for Beginner JavaScript Developers

Developer Skill Assessment Tool

When preparing interview questions for beginner-level JavaScript developers, focus on basic JavaScript syntax, array and string manipulation, objects and JSON, DOM manipulation, error handling and asynchronous programming. Here are 10 sample questions in this regard:

What will be the output of the below code:

Find the issue in the below code snippet.

Analyze the below code. Do you see any issue? If yes, what is that issue?

Create a JavaScript function that calculates the tip for a given bill amount and tip percentage. Bill amount and tip percentage will be input parameters while output will be calculated tip value.

What will be the output of below code snippet:

 Will the below code return any error? If yes, identify the error.

Implement a simple shopping cart system with features to add items, remove items and calculate the total price. Use objects to represent items, including properties for the item name, price and quantity. Implement features to add items to the cart, remove items and calculate the total cost.

Analyze the below code snippet and advise what will be the output:

Find the issue with the below code snippet:

Question 10

What issue exists in the below code:

Interview Questions for Mid-level JavaScript Developers

When designing interview questions for mid-level JavaScript developers, you should prepare challenges to test the understanding of advanced JavaScript concepts and problem-solving skills. Some areas that should be considered for evaluation include functional programming, asynchronous programming, promises, working with APIs and advanced JavaScript features. Find below 10 coding challenges which are suited to mid-level JavaScript developers:

What is the issue in the below code:

Develop a simple URL shortener service using JavaScript. Implement a function that takes a long URL as an input parameter and the output will be a shortened URL. Create a reverse function as well. The reverse function takes the shortened URL and returns the original long URL. You can use simple in-memory objects to store the mapping between long and short URLs.

Implement an autocomplete feature for a search input field. Given an array of words, write a function that suggests words based on the current input. The output of the function will be an array of suggested words that start with the input characters, limiting the number of suggestions (e.g., a maximum of 7 suggestions).

Will the below code return any error? If yes, what will be the error?

Develop a function that throttles another function, allowing it to be called at most once every specified interval (e.g., 300ms). The throttling function will have two input parameters. One will be the function to be throttled and the second will be the interval in milliseconds. The throttled function should be called with the same arguments as the original function.

What is wrong with the below code:

Design a simple meeting scheduler that finds the first available time slot for a meeting between two people. Given two arrays of busy time intervals and a meeting duration, create a function that returns the earliest available time slot for the meeting when both people will be available. Each interval is represented as an array of two integers, where the first integer is the start time and the second integer is the end time.

Interview Questions for Expert JavaScript Developers

When preparing coding challenges for expert-level JavaScript engineers, you should test the advanced features of the language and performance optimization techniques. Some of the areas to evaluate include advanced JavaScript features, code architecture, design patterns, performance optimization and security. Below we have presented 10 coding challenges for expert JavaScript developers:

Is there any security vulnerability in the below code? If yes, identify it:

Identify the output of the below code.

What is the possible performance issue in the below code?

Suggest the output of the below code:

Design a social media platform that contains features like sign up, creating a profile and posting status updates. Users should be able to follow other users and view their posts on a newsfeed.

What is wrong with the below call to the API?

What will be the output of below code snippet?

Design an online code editor where users can write, save and run JavaScript code. The editor should include features like syntax highlighting, auto-completion and error checking.

The below code snippet uses closures to implement a counter. How will you optimize it to minimize memory usage:

Develop a fitness tracker application where users can enter their daily exercise routines and track their progress over time. The application should allow users to set goals, view their progress and receive reminders.

Evaluating JavaScript developers at varying skill levels requires well-designed code challenges. Syntax, data types and functions are some basic concepts to test first. More sophisticated topics like object-oriented programming, algorithms and data structures should be included when testing mid-level engineers. Complex issues like performance optimization, security and design patterns should be used to evaluate expert-level developers.

This article has presented numerous examples of coding challenges to help hiring managers spot promising JavaScript developers at different levels of experience.

Test assessment tool

Further reading:

  • Java Coding Interview Questions
  • Python Coding Interview Questions
  • ReactJS Coding Interview Questions
  • C# Coding Interview Questions
  • C++ Coding Interview Questions
  • PHP Coding Interview Questions
  • 73 Advanced Coding Interview Questions
  • Share on Facebook
  • Email this Page
  • Share on LinkedIn

Download Interview guide PDF

Javascript interview questions, download pdf.

javascript problem solving questions and answers

JavaScript , created by Brendan Eich in 1995, is one of the most widely used web development languages. It was designed to build dynamic web pages at first. A script is a JS program that may be added to the HTML of any web page. When the page loads, these scripts execute automatically.

A language that was originally designed to build dynamic web pages may now be run on the server and on almost any device that has the JavaScript Engine installed.

After HTML and CSS, JavaScript is the third biggest web technology. JavaScript is a scripting language that may be used to construct online and mobile apps, web servers, games, and more. JavaScript is an object-oriented programming language that is used to generate websites and applications. It was created with the intention of being used in a browser. Even today, the server-side version of JavaScript known as Node.js may be used to create online and mobile apps, real-time applications, online streaming applications, and videogames. Javascript frameworks , often known as inbuilt libraries, may be used to construct desktop and mobile programs. Developers may save a lot of time on monotonous programming jobs by using these code libraries, allowing them to focus on the production work of development.

The InterviewBit team has compiled a thorough collection of top Javascript Interview Questions and Answers to assist you in acing your interview and landing your desired job as a Javascript Developer. 

JavaScript Interview Questions for Freshers

1. what are the different data types present in javascript.

To know the type of a JavaScript variable, we can use the typeof operator.

1. Primitive types

String - It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.

  • Number - It represents a number and can be written with or without decimals.
  • BigInt - This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers and is represented by adding “n” to an integer literal.
  • Boolean - It represents a logical entity and can have only two values : true or false. Booleans are generally used for conditional testing.
  • Undefined - When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.
  • Null - It represents a non-existent or a invalid value.
  • Symbol - It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.
  • typeof of primitive types :

2. Non-primitive types

  • Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used.
  • Object - Used to store collection of data.
Note- It is important to remember that any data type that is not a primitive data type, is of Object type in javascript.

2. Explain Hoisting in javascript.

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.

javascript problem solving questions and answers

This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global. Example 1:

doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope

Note - Variable initializations are not hoisted, only variable declarations are hoisted:
Note - To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:

3. Why do we use the word “debugger” in javascript?

The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.

4. Difference between “ == “ and “ === “ operators.

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

5. Difference between var and let keyword in javascript.

Some differences are  

  • From the very beginning, the 'var' keyword was used in JavaScript programming whereas the keyword 'let' was just added in 2015.
  • The keyword 'Var' has a function scope. Anywhere in the function, the variable specified using var is accessible but in ‘let’ the scope of a variable declared with the 'let' keyword is limited to the block in which it is declared. Let's start with a Block Scope.
  • In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
  • Software Dev
  • Data Science

6. Explain Implicit Type Coercion in javascript.

Implicit type coercion in javascript is the automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.

  • String coercion

String coercion takes place while using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type.

Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:

Let’s understand both the examples where we have added a number to a string,

When JavaScript sees that the operands of the expression x + y are of different types ( one being a number type and the other being a string type ), it converts the number type to the string type and then performs the operation. Since after conversion, both the variables are of string type, the ‘ + ‘ operator outputs the concatenated string “33” in the first example and “24Hello” in the second example.

Note - Type coercion also takes place when using the ‘ - ‘ operator, but the difference while using ‘ - ‘ operator is that, a string is converted to a number and then subtraction takes place.
  • Boolean Coercion

Boolean coercion takes place when using logical operators, ternary operators, if statements, and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values. Truthy values are those which will be converted (coerced) to true . Falsy values are those which will be converted to false . All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.

If statements:

  • Logical operators:

Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands. OR ( | | ) operator - If the first value is truthy, then the first value is returned. Otherwise, always the second value gets returned. AND ( && ) operator - If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned. Example:

  • Equality Coercion

Equality coercion takes place when using ‘ == ‘ operator. As we have stated before The ‘ == ‘ operator compares values and not types. While the above statement is a simple way to explain == operator, it’s not completely true The reality is that while using the ‘==’ operator, coercion takes place. The ‘==’ operator, converts both the operands to the same type and then compares them. Example:

Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.

7. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.

javascript problem solving questions and answers

Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.

For example, a variable that is assigned a number type can be converted to a string type:

8. What is NaN property in JavaScript?

NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.

typeof of NaN will return a Number .

To check if a value is NaN, we use the isNaN() function,

Note- isNaN() function converts the given value to a Number type, and then equates to NaN.

9. Explain passed by value and passed by reference.

In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference. For understanding passed by value and passed by reference, we need to understand what happens when we create a variable and assign a value to it,

In the above example, we created a variable x and assigned it a value of “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.

Assign operator behaves differently when dealing with primitive and non-primitive data types, Assign operator dealing with primitive types:

javascript problem solving questions and answers

In the above example, the assign operator knows that the value assigned to y is a primitive type (number type in this case), so when the second line code executes, where the value of y is assigned to z, the assign operator takes the value of y (234) and allocates a new space in the memory and returns the address. Therefore, variable z is not pointing to the location of variable y, instead, it is pointing to a new location in the memory.

From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created. Assign operator dealing with non-primitive types:

javascript problem solving questions and answers

In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.

From the above example, we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference). Therefore, non-primitive data types are always passed by reference.

10. What is an Immediately Invoked Function in JavaScript?

An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.

Syntax of IIFE :

To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE : The first set of parenthesis:

While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression. The second set of parenthesis:

From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:

Therefore to invoke the function, we use the second set of parenthesis.

11. What do you mean by strict mode in javascript and characteristics of javascript strict-mode?

In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a function in a "strict" operational environment. In most cases, this language is 'not particularly severe' when it comes to throwing errors. In 'Strict mode,' however, all forms of errors, including silent errors, will be thrown. As a result, debugging becomes a lot simpler.  Thus programmer's chances of making an error are lowered.

Characteristics of strict mode in javascript

  • Duplicate arguments are not allowed by developers.
  • In strict mode, you won't be able to use the JavaScript keyword as a parameter or function name.
  • The 'use strict' keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
  • Engineers will not be allowed to create global variables in 'Strict Mode.

12. Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher-order functions are a result of functions being first-class citizens in javascript.

Examples of higher-order functions:

13. Explain “this” keyword.

The “this” keyword refers to the object that the function is a property of. The value of the “this” keyword will always depend on the object that is invoking the function.\

Confused? Let’s understand the above statements by examples:

What do you think the output of the above code will be?

Note - Observe the line where we are invoking the function.

Check the definition again:

The “this” keyword refers to the object that the function is a property of.

In the above code, the function is a property of which object?

Since the function is invoked in the global context, the function is a property of the global object.

Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, this keyword will refer to the object obj , and hence the output will be “vivek”.

Can you guess the output here?

The output will be “akshay”.

Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .

The silly way to understand the “ this” keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot .

If there is no object before the dot-like in example1, the value of this keyword will be the global object.

Can you guess the output?

The output will be an error.

Although in the code above, this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.

14. What do you mean by Self Invoking Functions?

Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.

Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.

15. Explain call(), apply() and, bind() methods.

  • It’s a predefined method in javascript.
  • This method invokes a method (function) by specifying the owner object.
  • call() method allows an object to use the method (function) of another object.
  • call() accepts arguments:

apply() The apply method is similar to the call() method. The only difference is that, call() method takes arguments separately whereas, apply() method takes arguments as an array.

  • This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.
  • Example with arguments:

16. What is the difference between exec () and test () methods in javascript?

  • test () and exec () are RegExp expression methods used in javascript. 
  • We'll use exec () to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; else, it'll return an 'empty' result.
  • We will use a test () to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.

17. What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.

Example of a curried function:

For Example, if we have a function f(a,b) , then the function after currying, will be transformed to f(a)(b). By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked. Let’s see currying in action:

As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply , which takes in one parameter at a time.

18. What are some advantages of using External JavaScript?

External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the <head> or <body> element of the HTML file where the code is to be placed.  

Some advantages of external javascript are

  • It allows web designers and developers to collaborate on HTML and javascript files.
  • We can reuse the code.
  • Code readability is simple in external javascript.

19. Explain Scope and Scope Chain in javascript.

Scope in JS determines the accessibility of variables and functions at various parts of one’s code. In general terms, the scope will let us know at a given part of code, what are variables and functions we can or cannot access. There are three types of scopes in JS:

  • Global Scope
  • Local or Function Scope
  • Block Scope

Global Scope: Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.

Function Scope: Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.

Block Scope: Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.

Scope Chain: JavaScript engine also uses Scope to find variables. Let’s understand that using an example:

As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.

If the variable is not found in the global space as well, a reference error is thrown.

20. Explain Closures in JavaScript.

Closures are an ability of a function to remember the variables and functions that are declared in its outer scope.

Let’s understand closures by example:

Let’s understand the code above, The function randomFunc() gets executed and returns a function when we assign it to a variable:

The returned function is then executed when we invoke initialiseClosure:

The line of code above outputs “Vivian is awesome” and this is possible because of closure.

When the function randomFunc() runs, it seems that the returning function is using the variable obj1 inside it:

Therefore randomFunc(), instead of destroying the value of obj1 after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed. This ability of a function to store a variable for further reference even after it is executed is called Closure.

21. Mention some advantages of javascript.

There are many advantages of javascript. Some of them are 

  • Javascript is executed on the client-side as well as server-side also. There are a variety of Frontend Frameworks that you may study and utilize. However, if you want to use JavaScript on the backend, you'll need to learn NodeJS. It is currently the only JavaScript framework that may be used on the backend.
  • Javascript is a simple language to learn.
  • Web pages now have more functionality because of Javascript.
  • To the end-user, Javascript is quite quick.

22. What are object prototypes?

All javascript objects inherit properties from a prototype. For example,

  • Date objects inherit properties from the Date prototype
  • Math objects inherit properties from the Math prototype
  • Array objects inherit properties from the Array prototype.
  • On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.
  • A prototype is a blueprint of an object. The prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

javascript problem solving questions and answers

In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.

The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on.

23. What are callbacks?

A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.

Functions that are used as an argument to another function are called callback functions. Example:

  • In the code above, we are performing mathematical operations on the sum of two numbers. The operationOnSum function takes 3 arguments, the first number, the second number, and the operation that is to be performed on their sum (callback).
  • Both divideByHalf and multiplyBy2 functions are used as callback functions in the code above.
  • These callback functions will be executed only after the function operationOnSum is executed.
  • Therefore, a callback is a function that will be executed after another function gets executed.

24. What are the types of errors in javascript?

There are two types of errors in javascript.

  • Syntax error : Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
  • Logical error : Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.

25. What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned. Let’s understand memoization, by converting a simple function to a memoized function:

Note- Memoization is used for expensive function calls but in the following example, we are considering a simple function for understanding the concept of memoization better.

Consider the following function:

In the code above, we have written a function that adds the parameter to 256 and returns it. When we are calling the function addTo256 again with the same parameter (“20” in the case above), we are computing the result again for the same parameter. Computing the result with the same parameter, again and again, is not a big deal in the above case, but imagine if the function does some heavy-duty work, then, computing the result again and again with the same parameter will lead to wastage of time.

This is where memoization comes in, by using memoization we can store(cache) the computed results based on the parameters. If the same parameter is used again while invoking the function, instead of computing the result, we directly return the stored (cached) value.

Let’s convert the above function addTo256, to a memoized function:

In the code above, if we run the memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.

Note- Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

26. What is recursion in a programming language?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

Example of a recursive function: The following function calculates the sum of all the elements in an array by using recursion:

27. What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor functions are used.

Note- The name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.

In the code above, we have created a constructor function named Person. Whenever we want to create a new object of the type Person, We need to create it using the new keyword:

The above line of code will create a new object of the type Person. Constructor functions allow us to group similar objects.

28. What is DOM?

  • DOM stands for Document Object Model.  DOM is a programming interface for HTML and XML documents.
  • When the browser tries to render an HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.
  • Example of how HTML code gets converted to DOM:

javascript problem solving questions and answers

29. Which method is used to retrieve a character from a certain index?

The charAt() function of the JavaScript string finds a char element at the supplied index. The index number begins at 0 and continues up to n-1, Here n is the string length. The index value must be positive, higher than, or the same as the string length.

30. What do you mean by BOM?

Browser Object Model is known as BOM. It allows users to interact with the browser. A browser's initial object is a window. As a result, you may call all of the window's functions directly or by referencing the window. The document, history, screen, navigator, location, and other attributes are available in the window object.

31. What is the distinction between client-side and server-side JavaScript?

Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.

javascript problem solving questions and answers

Server-side JavaScript, involves the execution of JavaScript code on a server in response to client requests. It handles these requests and delivers the relevant response to the client, which may include client-side JavaScript for subsequent execution within the browser.

JavaScript Interview Questions for Experienced

1. what are arrow functions.

Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. Arrow functions can only be used as a function expression. Let’s compare the normal function declaration and the arrow function declaration in detail:

Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces { } can be omitted.

If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above. 

The biggest difference between the traditional function expression and the arrow function is the handling of this keyword. By general definition, this keyword always refers to the object that is calling the function. As you can see in the code above, obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the function.

In the arrow functions, there is no binding of this keyword. This keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.

2. What do mean by prototype design pattern?

The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. Also known as the Properties pattern, the Prototype pattern is used to create prototypes.

The introduction of business objects with parameters that match the database's default settings is a good example of where the Prototype pattern comes in handy. The default settings for a newly generated business object are stored in the prototype object.

The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.

3. Differences between declaring variables using var, let and const.

Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.

Let’s understand the differences with examples:

  • The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.
  • Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.
  • But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName. Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.

var vs let in functional scope

Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope. 

  • In javascript, a block means the code written inside the curly braces {} .
  • Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.
  • Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.

Const keyword

  • Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.

In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.

4. What is the rest parameter and spread operator?

Both rest parameter and spread operator were introduced in the ES6 version of javascript. Rest parameter ( … ):

  • It provides an improved way of handling the parameters of a function.
  • Using the rest parameter syntax, we can create functions that can take a variable number of arguments.
  • Any number of arguments will be converted into an array using the rest parameter.
  • It also helps in extracting all or some parts of the arguments.
  • Rest parameters can be used by applying three dots (...) before the parameters.

**Note- Rest parameter should always be used at the last parameter of a function:

  • Spread operator (…): Although the syntax of the spread operator is exactly the same as the rest parameter, the spread operator is used to spreading an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.
***Note- Key differences between rest parameter and spread operator: Rest parameter is used to take a variable number of arguments and turns them into an array while the spread operator takes an array or an object and spreads it Rest parameter is used in function declaration whereas the spread operator is used in function calls.

5. In JavaScript, how many different methods can you make an object?

In JavaScript, there are several ways to declare or construct an object.

  • using Class.
  • create Method.
  • Object Literals.
  • using Function.
  • Object Constructor.

6. What is the use of promises in javascript?

Promises are used to handle asynchronous operations in javascript. Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code. Promise object has four states -

  • Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  • Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
  • Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  • Settled - This state represents that the promise has been either rejected or fulfilled.

A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

javascript problem solving questions and answers

resolve is a function that will be called when the async operation has been successfully completed. reject is a function that will be called, when the async operation fails or if some error occurs. Example of a promise: Promises are used to handle asynchronous operations like server requests, for ease of understanding, we are using an operation to calculate the sum of three elements. In the function below, we are returning a promise inside a function:

In the code above, we are calculating the sum of three elements, if the length of the elements array is more than 3, a promise is rejected, or else the promise is resolved and the sum is returned.

We can consume any promise by attaching then() and catch() methods to the consumer.

javascript problem solving questions and answers

then() method is used to access the result when the promise is fulfilled.

catch() method is used to access the result/error when the promise is rejected. In the code below, we are consuming the promise:

7. What are classes in javascript?

Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript.  Below are the examples of how classes are declared and used:

Key points to remember about classes:

  • Unlike functions, classes are not hoisted. A class cannot be used before it is declared.
  • A class can inherit properties and methods from other classes by using the extend keyword.
  • All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. An error will be thrown if the strict mode rules are not followed.

8. What are generator functions?

Introduced in the ES6 version, generator functions are a special class of functions. They can be stopped midway and then continue from where they had stopped. Generator functions are declared with the function* keyword instead of the normal function keyword:

In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:

In the case of generator functions, when called, they do not execute the code, instead, they return a generator object . This generator object handles the execution.

The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value. For example, if we run the next() method on the above code:

As one can see the next method returns an object consisting of a value and done properties.  Value property represents the yielded value. Done property tells us whether the function code is finished or not. (Returns true if finished).

Generator functions are used to return iterators. Let’s see an example where an iterator is returned:

As you can see in the code above, the last line returns done:true , since the code reaches the return statement.

9. Explain WeakSet in javascript.

In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:

  • Weakset contains only objects and no other type.
  • An object inside the weakset is referenced weakly. This means, that if the object inside the weakset does not have a reference, it will be garbage collected.
  • Unlike Set, WeakSet only has three methods, add() , delete() and has() .

10. Why do we use callbacks?

A callback function is a method that is sent as an input to another function (now let us name this other function "thisFunction"), and it is performed inside the thisFunction after the function has completed execution.

JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.

11. Explain WeakMap in javascript.

In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:

  • The keys and values in weakmap should always be an object.
  • If there are no references to the object, the object will be garbage collected.

12. What is Object Destructuring?

Object destructuring is a new way to extract elements from an object or an array.

  • Object destructuring: Before ES6 version:

The same example using object destructuring:

As one can see, using object destructuring we have extracted all the elements inside an object in one line of code. If we want our new variable to have the same name as the property of an object we can remove the colon:

  • Array destructuring: Before ES6 version:

13. Difference between prototypal and classical inheritance

Programers build objects, which are representations of real-time entities, in traditional OO programming. Classes and objects are the two sorts of abstractions. A class is a generalization of an object, whereas an object is an abstraction of an actual thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles (class) are descended from vehicles (object).

Classical inheritance differs from prototypal inheritance in that classical inheritance is confined to classes that inherit from those remaining classes, but prototypal inheritance allows any object to be cloned via an object linking method. Despite going into too many specifics, a prototype essentially serves as a template for those other objects, whether they extend the parent object or not.

14. What is a Temporal Dead Zone?

Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords. It is a behaviour where we try to access a variable before it is initialized. Examples of temporal dead zone:

In the code above, both in the global scope and functional scope, we are trying to access variables that have not been declared yet. This is called the Temporal Dead Zone .

15. What do you mean by JavaScript Design Patterns?

JavaScript design patterns are repeatable approaches for errors that arise sometimes when building JavaScript browser applications. They truly assist us in making our code more stable.

They are divided mainly into 3 categories 

  • Creational Design Pattern
  • Structural Design Pattern
  • Behavioral Design Pattern.
  • Creational Design Pattern: The object generation mechanism is addressed by the JavaScript Creational Design Pattern. They aim to make items that are appropriate for a certain scenario.
  • Structural Design Pattern: The JavaScript Structural Design Pattern explains how the classes and objects we've generated so far can be combined to construct bigger frameworks. This pattern makes it easier to create relationships between items by defining a straightforward way to do so.
  • Behavioral Design Pattern: This design pattern highlights typical patterns of communication between objects in JavaScript. As a result, the communication may be carried out with greater freedom.

16. Is JavaScript a pass-by-reference or pass-by-value language?

The variable's data is always a reference for objects, hence it's always pass by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it. It appears to be pass by reference in this case. However, if you modify the values of the object variable, the change will not last, demonstrating that it is indeed passed by value.

17. Difference between Async/Await and Generators usage to achieve the same functionality.

  • Generator functions are run by their generator yield by yield which means one output at a time, whereas Async-await functions are executed sequentially one after another.
  • Async/await provides a certain use case for Generators easier to execute.
  • The output result of the Generator function is always value: X, done: Boolean, but the return value of the Async function is always an assurance or throws an error.

18. What are the primitive data types in JavaScript?

A primitive is a data type that isn't composed of other data types. It's only capable of displaying one value at a time. By definition, every primitive is a built-in data type (the compiler must be knowledgeable of them) nevertheless, not all built-in datasets are primitives. In JavaScript, there are 5 different forms of basic data. The following values are available:

19. What is the role of deferred scripts in JavaScript?

The processing of HTML code while the page loads are disabled by nature till the script hasn't halted. Your page will be affected if your network is a bit slow, or if the script is very hefty. When you use Deferred, the script waits for the HTML parser to finish before executing it. This reduces the time it takes for web pages to load, allowing them to appear more quickly.

20. What has to be done in order to put Lexical Scoping into practice?

To support lexical scoping, a JavaScript function object's internal state must include not just the function's code but also a reference to the current scope chain.

21. What is the purpose of the following JavaScript code?

Every executing function, code block, and script as a whole in JavaScript has a related object known as the Lexical Environment. The preceding code line returns the value in scope.

JavaScript Coding Interview Questions

1. guess the outputs of the following codes:.

  • Code 1 - Outputs 2 and 12 . Since, even though let variables are not hoisted, due to the async nature of javascript, the complete function code runs before the setTimeout function. Therefore, it has access to both x and y.
  • Code 2 - Outputs 3 , three times since variable declared with var keyword does not have block scope. Also, inside the for loop, the variable i is incremented first and then checked.
  • Code 3 - Output in the following order:

Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API, and therefore, the complete function executes before the setTimeout function can execute.

2. Guess the outputs of the following code:

Answers: Code 1 - Output will be {name: “Akki”}. Adding objects as properties of another object should be done carefully. Writing x[y] = {name:”Vivek”} , is same as writing x[‘object Object’] = {name:”Vivek”} , While setting a property of an object, javascript coerces the parameter into a string. Therefore, since y is an object, it will be converted to ‘object Object’. Both x[y] and x[z] are referencing the same property. Code 2 - Outputs in the following order:

Code 3 - Output in the following order due to equality coercion:

3. Guess the output of the following code:

Output is NaN . random() function has functional scope since x is declared and hoisted in the functional scope. Rewriting the random function will give a better idea about the output:

4. Guess the outputs of the following code:

Answers: Code 1 - Output in the following order:

Reason - The first output is undefined since when the function is invoked, it is invoked referencing the global object:

Code 2 - Outputs in the following order:

Since we are using the arrow function inside func2, this keyword refers to the global object. Code 3 - Outputs in the following order:

Only in the IIFE inside the function f , this keyword refers to the global/window object.  

5. Guess the outputs of the following code:

**note - code 2 and code 3 require you to modify the code, instead of guessing the output..

Answers - Code 1 - Outputs 45 . Even though a is defined in the outer function, due to closure the inner functions have access to it. Code 2 - This code can be modified by using closures,

Code 3 - Can be modified in two ways: Using let keyword:

Using closure:

6. Write a function that performs binary search on a sorted array.

function binarySearch ( arr,value,startPos,endPos ) { if (startPos > endPos) return - 1 ; let middleIndex = Math .floor(startPos+endPos)/ 2 ; if (arr[middleIndex] === value) return middleIndex; elsif ( arr[middleIndex] > value ) { return binarySearch(arr,value,startPos,middleIndex- 1 ); } else { return binarySearch(arr,value,middleIndex+ 1 ,endPos); } }  

7. Implement a function that returns an updated array with r right rotations on an array of integers a .

Given the following array: [2,3,4,5,7] Perform 3 right rotations: First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]

return [4,5,7,2,3]

8. Write the code for dynamically inserting new components.

<html> <head> <title>inserting new components dynamically</title> <script type="text/javascript"> function addNode () { var newP = document. createElement("p"); var textNode = document.createTextNode(" This is other node"); newP.appendChild(textNode); document.getElementById("parent1").appendChild(newP); } </script> </head> <body> <p id="parent1">firstP<p> </body> </html>

9. Write the code given If two strings are anagrams of one another, then return true.

var firstWord = "Deepak" ; var secondWord = "Aman" ; isAnagram(wordOne, wordTwo); // true function isAnagram ( one, two ) { //Change both words to lowercase for case insensitivity.. var a = one.toLowerCase(); var b = two.toLowerCase(); // Sort the strings, then combine the array to a string. Examine the outcomes. a = a.split( "" ).sort().join( "" ); b = b.split( "" ).sort().join( "" ); return a === b; }

10. Write the code to find the vowels

const findVowels = str => { let count = 0 const vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ] for ( let char of str.toLowerCase()) { if (vowels.includes(char)) { count++ } } return count }

11. In JavaScript, how do you turn an Object into an Array []?

let obj = { id : "1" , name : "user22" , age : "26" , work : "programmer" }; //Method 1: Convert the keys to Array using - Object.keys() console .log( Object .keys(obj)); // ["id", "name", "age", "work"] // Method 2 Converts the Values to Array using - Object.values() console .log( Object .values(obj)); // ["1", "user22r", "26", "programmer"] // Method 3 Converts both keys and values using - Object.entries() console .log( Object .entries(obj)); //[["id", "1"],["name", "user22"],["age", "26"],["work", “programmer"]]

12. What is the output of the following code?

It is preferable to keep the JavaScript, CSS, and HTML in distinct Separate 'javascript' files. Dividing the code and HTML sections will make them easier to understand and deal with. This strategy is also simpler for several programmers to use at the same time. JavaScript code is simple to update. Numerous pages can utilize the same group of JavaScript Codes. If we utilize External JavaScript scripts and need to alter the code, we must do it just once. So that we may utilize a number and maintain it much more easily. Remember that professional experience and expertise are only one aspect of recruitment. Previous experience and personal skills are both vital in landing (or finding the ideal applicant for the job.

Remember that many JavaScript structured interviews are free and have no one proper answer. Interviewers would like to know why you answered the way you did, not if you remembered the answer. Explain your answer process and be prepared to address it. If you're looking to further enhance your JavaScript skills, consider enrolling in this free JavaScript course by Scaler Topics to gain hands-on experience and improve your problem-solving abilities.

Recommended Resources

  • JavaScript Cheat Sheet: Basics to Advanced(2023)
  • Online Javascript Compiler
  • Top JavaScript Features You Must Know
  • 50 JavaScript MCQ With Answers
  • Top 15+ JavaScript Projects for Beginners to Advanced [With Source Code]
  • 9 Best JavaScript IDE & Source Code Editors [2023]
  • Top ES6 Interview Questions (2023)
  • 10 Best JavaScript Books for Beginners to Advanced [2023]
  • 30+ Top Node.js Interview Questions (2023)
  • Typescript vs Javascript: What’s The Difference?
  • Top 5 JavaScript Libraries You Must Know in 2023
  • Difference Between HTML and JavaScript
  • Javascript Vs jQuery: What’s the Difference? [2023]
  • Javascript Vs Python: What’s The Difference? [2023]
  • Difference Between Java and Javascript
  • Difference between Typescript and Javascript

Interview Guides

  • The Ultimate Guide to Acing Your Technical Interview
  • 300+ Must Do Coding Questions from Interviews
  • Mock Interview
  • InterviewBit - No.1 Resource for Tech Interview Preparation

Coding Problems

Javascript mcq.

Which of the following statements regarding JavaScript is true?

Which of the following JavaScript code snippets will provide the desired result?

In JavaScript, which of the following is not a bug?

JavaScript was created by which company?

What do you mean by block statement in JavaScript?

Argument class is

Which of these String object functions gives the calling data type transformed to upper case?

The JSON() method's property is

Which of the below do not belong in the JavaScript Data Types category?

The interpreter for Javascript is

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Solve common problems in your JavaScript code

The following links point to solutions to common problems you may encounter when writing JavaScript.

Common beginner's mistakes

Correct spelling and casing.

If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly.

Some common built-in browser functions that cause problems are:

Semicolon position

You need to make sure you don't place any semicolons incorrectly. For example:

There are a number of things that can go wrong with functions.

One of the most common errors is to declare the function, but not call it anywhere. For example:

This code won't do anything unless you call it with the following statement:

Function scope

Remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function.

Running code after a return statement

Remember also that when you return from a function, the JavaScript interpreter exits the function — no code after the return statement will run.

In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement".

Object notation versus normal assignment

When you assign something normally in JavaScript, you use a single equals sign, e.g.:

With Objects , however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. For example:

Basic definitions

  • What is JavaScript?
  • What is a variable?
  • What are strings?
  • What is an array?
  • What is a loop?
  • What is a function?
  • What is an event?
  • What is an object?
  • What is JSON?
  • What is a web API?
  • What is the DOM?

Basic use cases

  • How do you add JavaScript to your page?
  • How do you add comments to JavaScript code?
  • How do you declare a variable?
  • How do you initialize a variable with a value?
  • How do you update a variable's value? (also see Assignment operators )
  • What data types can values have in JavaScript?
  • What does 'loosely typed' mean?
  • What types of number do you have to deal with in web development?
  • How do you do basic math in JavaScript?
  • What is operator precedence, and how is it handled in JavaScript?
  • How do you increment and decrement values in JavaScript?
  • How do you compare values in JavaScript? (e.g. to see which one is bigger, or to see if one value is equal to another).
  • How do you create a string in JavaScript?
  • Do you have to use single quotes or double quotes?
  • How do you escape characters in strings?
  • How do you join strings together?
  • Can you join strings and numbers together?
  • How do you find the length of a string?
  • How do you find what character is at a certain position in a string?
  • How do you find and extract a specific substring from a string?
  • How do you change the case of a string?
  • How do you replace one specific substring with another?
  • How do you create an array?
  • How do you access and modify the items in an array? (this includes multidimensional arrays)
  • How do you find the length of an array?
  • How do you add items to an array?
  • How do you remove items from an array?
  • How do you split a string into array items, or join array items into a string?

Debugging JavaScript

  • What are the basic types of error?
  • What are browser developer tools, and how do you access them?
  • How do you log a value to the JavaScript console?
  • How do you use breakpoints and other JavaScript debugging features?

For more information on JavaScript debugging, see Handling common JavaScript problems . Also, see Other common errors for a description of common errors.

Making decisions in code

  • How do you execute different blocks of code, depending on a variable's value or other condition?
  • How do you use if ...else statements?
  • How do you nest one decision block inside another?
  • How do you use AND, OR, and NOT operators in JavaScript?
  • How do you conveniently handle a large number of choices for one condition?
  • How do you use a ternary operator to make a quick choice between two options based on a true or false test?

Looping/iteration

  • How do you run the same bit of code over and over again?
  • How do you exit a loop before the end if a certain condition is met?
  • How do you skip to the next iteration of a loop if a certain condition is met?
  • How do you use while and do...while loops?

Intermediate use cases

  • How do you find functions in the browser?
  • What is the difference between a function and a method?
  • How do you create your own functions?
  • How do you run (call, or invoke) a function?
  • What is an anonymous function?
  • How do you specify parameters (or arguments) when invoking a function?
  • What is function scope?
  • What are return values, and how do you use them?
  • How do you create an object?
  • What is dot notation?
  • What is bracket notation?
  • How do you get and set the methods and properties of an object?
  • What is this , in the context of an object?
  • What is object-oriented programming?
  • What are constructors and instances, and how do you create them?
  • What different ways are there to create objects in JavaScript?
  • How do you structure JSON data, and read it from JavaScript?
  • How can you load a JSON file into a page?
  • How do you convert a JSON object to a text string, and back again?
  • What are event handlers and how do you use them?
  • What are inline event handlers?
  • What does the addEventListener() function do, and how do you use it?
  • Which mechanism should I use to add event code to my web pages?
  • What are event objects, and how do you use them?
  • How do you prevent default event behavior?
  • How do events fire on nested elements? (event propagation, also related — event bubbling and capturing)
  • What is event delegation, and how does it work?

Object-oriented JavaScript

  • What are object prototypes?
  • What is the constructor property, and how can you use it?
  • How do you add methods to the constructor?
  • How do you create a new constructor that inherits its members from a parent constructor?
  • When should you use inheritance in JavaScript?
  • How do you manipulate the DOM (e.g. adding or removing elements) using JavaScript?

Arc Developer Career Blog

65 JavaScript Interview Questions & Answers to Prepare For (Beg to Adv)

javascript interview questions and answers for javascript developer interviews

Practice common basic, intermediate, and advanced JavaScript interview questions and answers with this comprehensive guide. Good luck!

When hiring dedicated Node.js developers , it’s crucial to evaluate their expertise in JavaScript. Use these JavaScript interview questions and answers to help you practice and test your (or another job candidate’s) understanding of this popular programming language used in numerous modern frameworks.

In this guide, we break down the most important and most common JavaScript interview questions to know into three sections:

Basic JavaScript Interview Questions

Intermediate javascript interview questions, advanced javascript interview questions.

But, we don’t just give you the technical answer — you can head to any JavaScript tutorial or JS learning website for those.

Rather, on top of the standard technical answer, we give you the reasoning behind the question: why is the interviewer asking me this? What do they really want to know by asking me this question? How can my interview answer best respond to their question?

And, at the end of the article (as well as a few places throughout), we’ll link you to some other helpful interview advice and job hunting guides.

Let’s get started!

Looking to hire the best remote developers? Explore  HireAI to see how you can:

⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 300,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

The following set of questions should test your (or another candidate’s) basic knowledge of JavaScript and some of its core features.

1. What are logical operators in JavaScript?

Logical operators allow developers to compare variables and perform tasks based on the result of the comparison. As a hiring manager, you’d ask this question to gauge the candidate’s familiarity with the language and its fundamental features. Your candidate should be able to explain each logical operator and their behavior – stepping through each operand and computing its output.

There are four logical operators in JavaScript:

  • ||  – OR
  • &&  – AND
  • !  – NOT
  • ??  – Nullish Coalescing (see next question)

The “OR” operator is represented by two vertical lines ( || ). In JavaScript, the “OR” operator evaluates the values from left to right and returns the first truthy value. If none of the values are truthy, the “OR” operator will return the last operand.

The “AND” operator is represented by two ampersands ( && ). In JavaScript, the “AND” operator evaluates the values from left to right and returns the first falsy value. If all the operands are true, the “AND” operator will return the last operand.

The “NOT” operator is represented by an exclamation mark ( ! ). the “NOT” operator accepts a single argument and returns the inverse of its boolean value. The argument is first converted into a boolean ( true  or  false ). The argument’s boolean value is then inverted and returned ( true  becomes  false  and vice versa).

2. What is the  nullish coalescing  operator in JavaScript?

Nullish coalescing is an addition to JavaScript that helps provide a nicer and more concise syntax for getting the first “defined” value. The candidate should be able to explain what nullish coalescing is at a high-level and how to use the operator when asked this JS interview question.

Nullish coalescing is a JavaScript logical operator represented by two question marks ( ?? ). Nullish coalescing is an operator that returns the first “defined” value. “defined” here refers to an expression whose value is neither  null  nor  undefined .

Let’s look at how the operator works.

The output of the code above is as follows:

  • if a is defined, the value of a is returned
  • if a isn’t defined, the value of b is returned

Let’s look at a few examples of this operator when given a different set of arguments.

3. What is the difference between  ==  and  ===  operators?

JavaScript has two ways to test equality. Understanding the subtle difference between the two methods is important to prevent misusing each method. The candidate should be able to explain the differences and demonstrate a basic understanding of each method’s usage.

Both double-equals ( == ) and triple-equals ( === ) are comparison operators meant to compare the equality of two values.

Double-equals only compares the value of the element. Double-equals does type coercion, where the type of the variables is converted to a common type before checking their values. In short, the double-equals operator will return  true  for any two variables with the same value regardless of their type.

Triple-equals on the other hand, check for  strict equality  – both the value and type of the element being compared. Both the value and type of being compared has to match to satisfy the triple-equal operator

Read More : Common Interview Questions for Software Developer Jobs (Non-Technical)

4. What is a spread operator?

The spread operator is a feature from ES6 to help unpack an element. Candidates being asked this interview question on JavaScript should be able to demonstrate an understanding of how the spread operator expands an element – being able to come up with the output of a spread operator.

Spread  operator allows iterables such as arrays, objects, and strings to be expanded into single arguments. The spread operator is denoted by three dots ( ... ) followed by the variable to be expanded.

Let’s look at an example where we combine two arrays using the spread operator. Below we have a  male  and  female  array containing a few strings each. The  combined  array combines the expanded  male  and  female  array, creating a single array with the contents from both  male  and  female .

5. Explain loops in JavaScript.

We often require repeat actions. Loops are a way to execute the same code multiple times. The candidate should be able to explain how to use loops in JavaScript. An ideal answer should include the pros and cons of each looping method and its respective applications.

There are two main ways to create loops in JavaScript –  while  and  for . Both methods consist of a condition to stop the loop and a “loop body”, the code that will be executed multiple times.

while  loop

while  loops are typically used when the “loop body” needs to be repeated an unknown number of times until the condition is met.

The code snippet below shows a simple while loop that prints the value of  i  on every iteration and stops when  i  is equal to 3.

for  loop

A  for  loop, on the other hand, is better suited for executing the “loop body” a fixed number of times.

The same loop in the previous code snippet can be re-written using a  for  loop this way:

6. Explain the “this” keyword.

The  this  keyword is widely used in JavaScript applications. It behaves differently compared to other languages such as Java and Python. The candidate should have a thorough understanding of how the  this  keyword works and how it relates to its context.

The  this  keyword behaves differently depending on the caller’s context. Let’s look at a few contexts and what the  this  keyword refers to in each one

Global context

Global context refers to anything outside of any function – global object.  this  refers to the  window  object in web browsers and  global  object in Node.js applications.

If you assign a property to the  this  object in a web browser, JavaScript will add that property to the  window  object.

Function context

Functions can be invoked in four different ways.

Function invocation

Method invocation

Constructor invocation

Indirect invocation

Each of the invocations results in a different  this  behavior.

Depending on whether you are using “strict mode” or not, the  this  keyword refers to different values.

By default, the  this  keyword refers to the  window  or  global  object depending on where you are running the application.

In “strict mode”, JavaScript sets the  this  keyword to  undefined .

When you call a method of an object ( getName  in the example below), the  this  keyword is set to the object that owns the method ( user  in the example below).

Constructor invocation is when the  new  keyword is used to create a new instance of a function object.

The  new User('Bob')  is a constructor invocation of the  User  function where a new instance of the  User  function is created. The  this  keyword in this case refers to the newly created object.

Indirect invocation is when the callee of the function uses the  call  or  apply  keyword to call a function. Both these methods allow passing in the  this  value ( bob  and  adam  in the example below) as a parameter.

The  apply  keyword is identical to the  call  keyword above. Instead of accepting a single value as the second parameter, the  apply  keyword expects an array of values.

Read More : 31 Questions to Ask at an Interview for Software Development Jobs

7. What are the differences between  call ,  apply , and  bind ?

JavaScript has multiple ways to indirectly invoke a function. Your candidate needs to understand the differences between each and their use cases. You, as the candidate, should be able to explain not only their differences conceptually but also their use case and the reason behind it.

call ,  apply , and  bind  are different methods to tie a function to an object and call the function within the specified context.

The  call  method invokes the function with the specified context – the function is called as if it’s part of the object.

The function  sayHello  in the example below references  this.name  which is part of the  user  object (out of the scope of the  sayHello  function). We can use the  call  function and pass in the  user  object as the first argument to tie the  sayHello  function and the  user  object momentarily, giving it access to the  this.name  property.

The  apply  method is identical to the  call  method with the difference being in how each method accepts their arguments. The  call  method accepts an argument list, whereas the  apply  method accepts an array of arguments.

Using the same example as above, we can convert the  call  method to  apply  by wrapping the function’s arguments (excluding the context –  user ) in an array before passing it to  apply  method.

Unlike  call  and  apply , the  bind  method doesn’t execute the function immediately. Instead, it returns a function that is tied to the object that can be executed later.

Let’s update the example again to use the  bind  method. We’ll first bind the  sayHello  function to the  user  object and assign it to a new variable ( helloBill ). We can then invoke that function calling it as you would a regular function.

8. What are anonymous functions in JavaScript?

Anonymous functions serve numerous purposes in JavaScript. You might ask standard JavaScript interview questions like this one to gauge your candidates’ knowledge of functions in JavaScript and the various ways a function can be created and used. The candidate should be able to explain the difference between anonymous functions and other types of functions and what they are commonly used for

An anonymous function  is a function that does not have any name associated with it. We usually use the  function  keyword followed by the function’s name to define a function in JavaScript. Anonymous functions omit the function name, making it not accessible after its creation.

An anonymous function can only be accessed by a variable. The anonymous nature of the function makes it great for passing in functions as arguments to other functions (higher-order functions) and functions that are invoked immediately upon initialization.

The following snippet is an example of an anonymous function that is assigned to a variable ( sayHello ). The function can then be called by calling the variable name ( sayHello ) with the required arguments.

9. What is  hoisting  in JavaScript?

Hoisting allows functions to be used safely before they are declared. This question will test the candidate’s familiarity with the JavaScript language and how classes, functions, and variables are interpreted by JavaScript. A basic understanding of hoisting can prevent unexpected errors caused by an incorrect order of declaration, initialization, and reference of a property. You may get other JavaScript hoisting interview questions, so study up!

Hoisting  refers to the process where the interpreter moves the declaration of classes, functions, or variables to the top of their scope, before their execution.

Hoisting allows developers to reference variables, functions, and classes before they are declared. Without hoisting, the order of the example below would need to be reversed, with the function declaration first, followed by the caller.

However, JavaScript only hoists its declarations, not their initializations. Referencing a variable before its initialization would return the variable’s default value ( undefined  for variables declared using the  var  keyword).

Read More : 8 Common Interview Mistakes Remote Software Developers Make

10. What is a callback function in JavaScript?

JavaScript runs code sequentially from the top-down. However, sometimes, we need code to run after something has happened (i.e. asynchronous operations). Callback functions are a way to make sure a function runs only after the set of operations is completed. A candidate should be able to explain both how callback functions work and how it relates to asynchronous programming.

A  callback function  is a function passed into another function as an argument. The callback function is then invoked inside the callee to complete an action.

The example below shows how the callback function is passed into and executed by another function. The last line ( greetPerson(sayHello) ) passes the  sayHello  function to the  greetPerson  function.  greetPerson  then executes the  sayHello  function by calling the  callback  variable, passing in the  name  value returned by the  prompt  function.

11. What are Promises in JavaScript?

Promises are an effective way to handle asynchronous operations in JavaScript. A candidate should be able to demonstrate a high-level understanding of Promises and how they handle asynchronous operations. An ideal answer would include the tradeoffs of using Promises and how they compare to callbacks and events.

A Promise is a proxy for a value not necessarily known when the promise is created. A promise is a way to handle asynchronous operations in JavaScript. You can think of Promises as an alternative to callbacks and events.

Promises are ideal for handling multiple asynchronous operations, providing a better flow of control definition and error handling.

Let’s look at an example of a Promise that waits for a  setTimeout  to complete:

12. What are the different states of a Promise?

Understanding the different states of a promise is important when dealing with promises to avoid unwanted side effects. You might ask this question to gain insight into the candidate’s familiarity with promises beyond the high-level concept.

Because of the asynchronous nature of Promises, a Promise has four states:

  • Pending  – Promise’s initial state, waiting for the operation to complete
  • Fulfilled  – Promise’s operation was completed successfully
  • Rejected  – Promise’s operation failed
  • Settled  – Promise is either fulfilled or rejected

Read More : 8 Behavioral Interview Questions Asked by Top Tech Companies

13. What is Promise chaining?

Promise chaining is a common requirement when working with multiple Promises that depend on each other. A candidate should ideally be able to explain both what promise chaining is and how it is done in JavaScript.

One of the benefits of Promises is its chaining ability. A Promise can be chained using the  then  and  catch  functions. The  then  function will be called when the Promise completes successfully (fulfilled) whereas the  catch  function will be called when the Promise failed (rejected).

Each  then  and  catch  block can contain more Promises and be further chained, providing you with granular control over how each asynchronous operation should be executed.

Let’s look at an example of chaining two Promises that waits for one second between each execution.

The first Promise in the code snippet above waits for one second before returning a result of  1 . The code then goes to the  then  block where it executes the second Promise, waiting for another second before returning a result of  2 .

14. What is  Promise.all ?

JavaScript interview questions like this one might be asked as a follow-up to the Promise chaining question. JavaScript provides several utility functions that help with chaining Promises –  Promise.all  being one of them. A candidate should be able to describe the function of this type of Promise and also how it alters the flow of the asynchronous functions.

Promise.all  is a type of Promise that accepts an array of Promises and waits for each Promise to resolve.  Promise.all  resolves once each of the Promise inputs resolves, emitting an array of results in the  then  block. A rejected Promise in the input will cause the  Promise.all  Promise to also get rejected.

The example below shows how the  Promise.all  function is used to execute two Promises –  Promise1  and  Promise2 , with a  then  block to capture the results of each Promise and a  catch  block to handle any errors.

15. Explain async/await in JavaScript.

Async and await are special syntax to work with Promises. In addition to the “what”, as an interviewer, you might also want to look for practical examples of async and await usages and how it differs from the Promise  then  syntax.

The  async  keyword is placed before a function to denote that the function is asynchronous and can be used as a Promise.

The  await  keyword, on the other hand, tells JavaScript to wait for the async operation to complete before proceeding to the next task in the function. The  await  keyword can only be used in an  async  function.

Line 6 in the code snippet below pauses the function execution as it waits for the promise to resolve. Once the promise resolves, it will continue the execution, assigning the result of the promise to the  result  variable.

Read More : 10+ Tips for Preparing for a Remote Software Developer Zoom Interview

Check out our entire set of software development interview questions to help you hire the best developers you possibly can.

  • JavaScript Interview Questions
  • Machine Learning Interview Questions
  • MongoDB Interview Questions
  • TypeScript Interview Questions
  • Selenium Interview Questions
  • Spring Interview Questions
  • Data Engineer Interview Questions
  • React Interview Questions
  • Data Analyst Interview Questions
  • Vue Interview Questions
  • SQL Interview Questions
  • DevOps Interview Questions
  • Engineering Manager Interview Questions
  • Java Interview Questions
  • PHP Interview Questions
  • Ruby on Rails Interview Questions
  • Angular Interview Questions
  • Android Interview Questions
  • Data Warehouse Interview Questions

If you’re a developer, familiarize yourself with the non-technical interview questions commonly asked in the first round by HR recruiters and the questions to ask your interviewer !

Arc is the radically different remote job search platform for developers where companies apply to you. We’ll feature you to great global startups and tech companies hiring remotely so you can land a great remote job in 14 days. We make it easier than ever for software developers and engineers to find great remote jobs. Sign up today and get started .

More Basic JavaScript Interview Questions

Before we wrap this section up and get to the intermediate questions, here are a few other JavaScript basic interview questions you might want to ask your candidate during an interview:

  • What are self-invoking functions?
  • What is the purpose of the  race  method in a JavaScript Promise?
  • What is a pure function?
  • What are  break  and  continue  statements?
  • What is variable shadowing in JavaScript?
  • What is an event loop?
  • What is an event flow?
  • How do you sort elements in an array in JavaScript?
  • What is a debugger statement?
  • What is a short circuit condition?

The following questions should test the candidate’s intermediate knowledge of JavaScript and some of its widely used features.

1. What are  rest parameters ?

The rest parameter is a JavaScript feature to provide a way to represent variadic functions in JavaScript. The candidate should be able to demonstrate an understanding of how the rest operator is used in a function and how its contents can be accessed.

The  rest parameter  syntax allows a function to accept an indefinite number of arguments as an array. The  rest  operator puts the contents of the variable after the rest operator into an array (rest parameter can only be used as the last parameter of a function).

Rest operator is represented by three dots ( ... ) followed by the variable name. The variable can then be used to access the array containing the contents of the function’s arguments.

The example below shows a function that accepts two parameters –  greeting  and  name  (with a rest operator). The rest operator on the  name  argument tells JavaScript to add any arguments from the second argument forward into an array called  name .

2. What is  memoization  in JavaScript?

Optimization of processes becomes a necessity as applications grow and begin to perform heavier tasks. Memoization is an optimization technique that helps speed up expensive function calls using cached results. Understanding optimization techniques is important to keep your code fast and efficient. Your candidate should be able to explain memoization and how it relates to code optimization in general.

Memoization  is an optimization technique that speeds up your code by storing the results of expensive function calls and reusing the stored result when the same input occurs again.

An expensive function refers to functions that consume a lot of resources (time and memory) during their execution due to heavy computation.

The result is immediately stored in a cache when an expensive function is called. When the same function is called again with the same parameters, it skips the computation required and returns the cached value instead. This process significantly reduces the time and memory your application consumes as the function doesn’t have to redo any calculations or computations that it has done previously.

3. What is  currying  in JavaScript?

Currying is an advanced technique of working with functions based on a concept from lambda calculus. You might ask intermediate JavaScript interview questions similar to this one to get an insight into the candidate’s level of understanding of functions in JavaScript. The candidate should be able to explain the concept of currying and how a function is decomposed and transformed following this concept.

Currying  is a transformation of functions that translates a function from callable as  f(a, b, c)  into callable as  f(a)(b)(c) . In other words, currying a function means the function takes one argument at a time and returns a new function expecting the next argument. Instead of taking all arguments at the same time, currying decomposes the function into a sequence of functions with a single argument.

Let’s look at an example of two functions that accepts three arguments and returns their sum. The first function ( ) is a regular function, whereas the second function ( ) is the curried version.

4. How do you empty a JavaScript array?

Arrays are widely used in JavaScript, making understanding their behavior and possible operations crucial when working with JavaScript. You might ask a JS question like this to gauge the candidate’s familiarity with JavaScript arrays and their operators. The candidate should be ready to explain a couple of different approaches and how they work at a high level.

There are various ways to empty an array in JavaScript. Below are a few common ways to do it.

  • Set the target array to an empty array.
  • Set the length of the target array to  0 .
  • Use the  splice  method to update the target array’s contents.

5. What is a  WeakMap  in JavaScript?

A WeakMap is a map where the keys are weak – values are garbage collected when there are no more references to the key/value. The candidate should be able to explain what a WeakMap is along with their use case. You might also be looking to test the candidate’s understanding of the garbage collection mechanism, so make sure they explain how WeakMap relates to garbage collection in JavaScript.

By definition, a  WeakMap  is a collection of key/value pairs whose keys must be objects, with values of any arbitrary JavaScript type, and which do not create strong references to its keys.

A WeakMap provides a way to extend objects externally without interfering with JavaScript’s garbage collection mechanism. Once an object used as a key is collected, the object’s corresponding values in any WeakMap become candidates for garbage collection as well.

A WeakMap is especially useful when mapping keys to information about the key is valuable  only  if the key has not been garbage collected.

6. What is  typecasting  in JavaScript?

Converting between different data types is common in programming in general, and this is important for your candidate to get right. These could be when receiving a value from an external API, a user input, a third-party library, etc. A candidate should be able to demonstrate a basic understanding of what typecasting is and how to utilize the typecasts provided by JavaScript to convert between various data types.

Typecasting  or  coercion  means to change the data type of a value to another data type. For example, a conversion from a string to an integer or vice versa.

Coercion can either be implicit or explicit. Implicit coercion is when the type conversion is automatic, whereas explicit coercion is when a developer explicitly writes code to convert the type of a value. The latter is also known as typecasting.

There are three typecasts provided by JavaScript:

  • Boolean(value)  – Casts the input value to a boolean value
  • Number(value)  – Casts the input value to a float or integer value
  • String(value)  – Casts the input value to a string

7. What are the various types of errors in JavaScript?

Every developer is bound to run into errors when programming in any language. JavaScript is no different. Debugging and resolving these errors are usually part of every developer’s day. Identifying the different error types can significantly help the developer narrow down the problem. The candidate should be able to identify and differentiate between the errors described below when asked this important JS interview question.

There are three types of errors in JavaScript:

  • Syntax errors  – Errors that occur at interpretation time such as during the loading of a web page due to incorrect syntax in the code.
  • Runtime errors  – Errors that occur during the runtime of the program after it is interpreted by the compiler. Calling functions that don’t exist is a common cause of this type of error.
  • Logical Errors  – Errors caused by the code’s logic itself. They are syntactically correct and don’t necessarily cause runtime errors. To think of this in terms of a sentence in the English language – the vocabulary and grammar of the sentence are correct, however, the meaning of the sentence is incorrect.

8. What is  event bubbling  in JavaScript?

Dealing with events is unavoidable, especially when working with the web. Event bubbling is an important concept that is commonly used either directly or via a framework or library. The candidate should be able to demonstrate a high-level understanding of what event bubbling is and how events work in JavaScript.

Event bubbling  is a way of event propagation in the HTML DOM API, where events are handled from starting from the innermost element propagating outwards to its parent elements.

Let’s look at an example where an event occurs in a nested element where both elements have a registered event handler for the triggered event. Event bubbling causes the event to be captured and handled by the innermost element first. It is then propagated to the outer elements.

9. What is  event capturing  in JavaScript?

Similar to the previous question on event bubbling, event capturing is the opposite of event bubbling. You might ask this question as a follow-up to previous tough JavaScript interview questions to gauge the candidate’s understanding of events in JavaScript.

Event capturing  is another way of event propagation in the HTML DOM API. Unlike event bubbling, event capturing propagates an event from the outermost element to the target element.

Bubbling is disabled by default on event listeners. To use event capturing, we will need to enable bubbling by passing  true  to the third argument of the  addEventListener  function.

10. What are the different ways an HTML element can be accessed in JavaScript?

If you are working with HTML with JavaScript, you will often find the need to access HTML elements from JavaScript. Although frameworks and libraries have abstractions that ease this process, a fundamental understanding of this is important. As a hiring manager or tech recruiter,  you might ask this JS interview question to get an insight into the candidate’s level of understanding of accessing HTML elements beyond what the various frameworks and libraries offer.

There are four ways to access an HTML element in JavaScript:

  • getElementById('idName')  – Returns an element with the specified  idName
  • getElementByClass('className')  – Returns all the elements containing the specified  className
  • getElementsByTagName('tagName')  – Returns all the elements that contains the specified  tagName
  • querySelector('selectorName')  – Returns the first element that contains the CSS style selector sepecified

More Intermediate JavaScript Interview Questions to Practice

Here are a few other intermediate JavaScript interview questions you might want to ask your candidates:

  • How do you escape characters in JavaScript?
  • What are JavaScript Cookies?
  • What are the difference between  escape()  and  unescape()  functions?
  • What is a microtask in JavaScript?
  • What are higher-order functions in JavaScript?
  • What are the different types of native errors in JavaScript?
  • What is the difference between attributes and properties in JavaScript?
  • What are the main differences between a  forEach  loop and a  map  loop?
  • How do you compare two objects in JavaScript?
  • How do you remove duplicates in a JavaScript array?

javascript problem solving questions and answers

The following set of advanced JavaScript interview questions should test the candidate’s advanced knowledge of JavaScript and some of its more advanced concepts and features.

1. What is a  closure  in JavaScript?

Closures in JavaScript lets you associate data with a function that operates on that data. This has close ties to the object-oriented programming concept of objects allowing you to associate its properties with one or more methods. The candidate should not only explain what a closure is but also be able to provide examples and use cases where closures are useful.

A  closure  is an inner function that has access to the variables in the enclosing/outer function’s scope. The closure has access to variables from three scopes:

  • within its own scope
  • within the enclosing function’s scope
  • global variables

Closures are particularly useful on the web because of the web’s event-based nature. A common pattern in front-end JavaScript is as follows: you define a behavior, then attach it to an event that is triggered by user input. An example of this is a click event handler.

Below is an example of how a closure is used to change the document body’s background color when the  targetElement  is clicked. The  changeBackground  function returns an inner function that sets the document body’s style.

2. What does the  instanceof  operator do?

Since we don’t explicitly define a type when we declare a variable, we sometimes need to know what the type of the variable is before performing any operation with it. The  instanceof  operator provides an easy way to perform a check on the variable’s type at run time. The candidate should be able to explain what is the  instanceof  operator and also its applications and usage.

The  instanceof  operator checks whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In other words, the  instanceof  operator checks if the object is an instance of a class or not at run time.

The example below shows how the  instanceof  operator is used to test the type of the variable  users .

3. How do you create a  shallow copy  of an object?

Cloning an object in JavaScript is a common task especially when you are working with objects. The candidate should be able to demonstrate a couple of ways to create a shallow copy and what characteristics the shallow copy has as it relates to the original object. A follow-up JS question an interviewer might ask is how to create a deep copy of an object.

Deep copying means that the value of the new variable is disconnected from the original variable while a shallow copy means that some values are still connected to the original variable.

First of all, a  deep copy  is a copy of an object completely disconnected from the original variable. A  shallow copy  on the other hand is a copy of the original variable where some values are still connected to the original variable.

There are two main ways to create a shallow copy of an object in JavaScript:

1. Using the spread operator

2. Using `Object.assign()

4. What is the difference between  Object.freeze()  and  const ?

Developers work with a lot of objects in JavaScript. Understanding how objects work is very important and can help avoid bugs and unexpected behaviors that arise from using objects incorrectly. You might ask a question like this to gauge the candidate’s understanding on JavaScript objects and its mutability-related behavior. The candidate should be able to explain the key difference between  Object.freeze()  and  const  along with their respective applications.

Both  Object.freeze()  and  const  relates to the immutability of the object. However, they each address different aspects of the object’s immutability.

const  creates immutable bindings. A variable declared with the  const  keyword can’t be assigned a new value.

Object.freeze() , on the other hand, makes the contents of the object immutable. You can’t modify the properties in the object.

5. What is  Strict mode  in JavaScript?

Strict mode is a feature of JavaScript ES5 to enforce stricter rules. The strict mode would cause code errors that would have been ignored or failed silently to generate errors. It is often good practice to use strict mode, though every use case is different. Your candidate should be able to explain the differences between using JavaScript’s strict mode and not.

Strict mode  is a mode in JavaScript to enforce stricter parsing and error handling on your JavaScript code.

The main benefit of using strict mode is catching errors early and making debugging your code easier. Common errors such as assigning a value to an undeclared variable would throw an error in strict mode alerting you that there is something wrong in your code. You can master the art of secure coding with insights into anti-debugging techniques . This will safeguard your JavaScript applications and elevate your programming prowess to create robust, resilient software.

You need to add the string “use strict” above the file to enable strict mode for that file.

6. What is the difference between  local storage  and  session storage ?

The web storage API contains two great tools to save key/value pairs – local storage and session storage. These are often used as an alternative to cookies. You might ask this difficult JavaScript interview question to get a better understanding of the candidate’s familiarity with client-side storage .

Local storage  is a read-only property of the window interface to access a storage object. The stored data is saved indefinitely across browser sessions. Data stored in local storage is only cleared when removed explicitly through the browser’s settings or programmatically by the application.

Session storage  is similar to local storage with the key difference being the data stored’s expiration time. Data stored in session storage gets cleared when the page session ends. A page session lasts as long as the tab or browser is open and persists between page reloads and restores.

7. What is the  Temporal Dead Zone  in JavaScript?

Temporal dead zone is a concept closely tied to hoisting. You might ask this question to gain an insight into your candidates’ familiarity with how hoisting works in JavaScript and JavaScript’s initialization process. Make sure your web developer know what temporal dead zone is and how to look for a temporal dead zone’s starts and ends.

In ES6, variables declared using  let  and  const  are hoisted similar to  var ,  class  and  function . However, there is a period between the variable’s declaration and when it enters scope where the variable can’t be accessed. This period is called the  Temporal dead zone  (TDZ).

Below is an example where the variable  name  is declared using the  let  keyword but is assigned a value later in the code. The temporal dead zone is the period before the  name  variable is declared. Attempting to access the variable while in the temporal dead zone will throw a reference error.

8. What is a  generator  in JavaScript?

Generators when combined with Promises are a powerful tool for asynchronous programming as they help avoid problems associated with callbacks such as inversion of control and callback hell. The candidate should have a high-level understanding of what a generator is, how generator functions work in JavaScript, and their use cases .

Generators  are functions that can be exited and re-entered at a later time. These type of functions saves and persists their context and variable-bindings across re-entrances.

A generator function is defined by a  function*  (keyword  function  followed by an asterisk ( * )) declaration.

When a generator function is initially called, it returns a type of iterator called a generator. The value is then consumed by calling the generator’s next method. The generator function continues its execution until it encounters the yield keyword.

There is no limit to the number of times a generator function can be called, however, each generator can only be iterated once.

Below is an example of a simple generator function that increments the current index and returns the incremented value.

9. What is the  Prototype Design Pattern ?

This is a different type of question compared to the others you’ve seen in this section. This question is more conceptual, touching on design patterns, instead of discussing the features of JavaScript and how to perform a certain task. There are various design patterns used in software engineering, however since JavaScript is a prototypal language, a question about Prototype Design Pattern might be more relevant.

As the hiring manager, you might ask this question to test your candidates’ general knowledge of design patterns, their familiarity with the prototype design pattern, and how it could be used in the context of JavaScript._

The  Prototype Design Pattern , also known as Properties Pattern is a creational design pattern based on prototypal inheritance. When an object is created, it acts as a prototype for other objects. You can think of the prototype object as a blueprint for other objects the constructor creates – the properties defined in the prototype object will also be present in the cloned object it creates.

The prototype model is mainly used for creating objects in performance-intensive situations. The prototype pattern helps eliminate the overhead of initializing an object.

Common applications of the prototype pattern are when you have a system independent of how its contents are created or when creating objects from a database whose values are copied to the newly created object.

10. What role do  deferred scripts  play in JavaScript?

This is an optimization question related to how JavaScript code is loaded. An understanding of how to optimize the loading of the script and its execution is important as an app grows and the delay becomes more and more noticeable. You may ask this type of question to test the candidate’s knowledge of the browser’s page load process and how familiar the candidate is with optimizing this process.

When a page loads, the browser starts to parse the HTML code. By default, when the browser runs into a script during the parsing process, it pauses processing the HTML code and starts executing the script. The browser then resumes parsing the HTML code once the script is done executing.

A slow server or a bulky script will cause a delay in the page load.  Deferred scripts  delay the script’s execution until the document has been parsed. This delay in the script’s execution results in a reduction in the load time of the webpage.

More JavaScript Advanced Interview Questions to Practice

Before we wrap this article up, here are a few other JavaScript advanced interview questions you might ask your candidates in your upcoming interview.

  • How does JavaScript garbage collector work?
  • What is a proper tail call?
  • What is the difference between shallow and deep copy?
  • How do you flatten a multi-dimensional array?
  • What is the purpose of  queueMicrotask ?
  • What is the difference between shim and polyfill?
  • What is the use of  preventDefault  method?
  • What is a proxy object?
  • What are JavaScript accessors? -What are the differences between mutable and immutable objects?

Whether you’re a hiring manager looking for the ideal candidate or a developer preparing for an interview, we hope these JavaScript interview questions help you through the process.

Keep in mind that technical skills and knowledge are only one part of the hiring process. Past experience and soft skills are equally important to make sure you land (or find the right candidate for) the job.

Keep in mind that many JavaScript interview questions are open-ended and don’t have one correct answer. When you’re interviewing a potential candidate, make sure to focus on evaluating not only their technical expertise but also on their thought process and problem-solving skills. 

You can also explore HireAI to skip the line and:

⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 250,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Read More : How to Write a Great Thank-You Email After an Interview

' src=

William Juan

Web & Mobile Front-End Developer

William is a front-end developer working primarily in the web and hybrid mobile spaces. The majority of his work has revolved around the Angular ecosystem, including working with other Angular-related frameworks such as NativeScript and Ionic. At Arc, he contributes the expertise he's gained over years as a writer on software development careers.

Join the discussion Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Further reading

how to answer Spring Interview Questions

20 Spring Interview Questions and Answers to Know (With MVC & Boot)

software developer or software engineering questions to ask tech recruiters

8 Questions to Ask Recruiters Before Committing to the Dev Hiring Process

how to answer Angular Interview Questions for AngularJS

29 Angular Interview Questions and Answers to Practice & Prepare For

questions to ask at an interview for software developers interview questions to ask

31 Questions to Ask at an Interview for Software Development Jobs

how to answer Selenium Interview Questions

21 Selenium Interview Questions & Answers to Know (Basic to Advanced)

best data analysis interview questions to practice for data analytics jobs

10 Data Analyst Interview Questions & Answers You Should Prepare For

time-travel-ticket

javascript problem solving questions and answers

10 Common JavaScript Interview Questions (and Answers)

Ravi Sharma

Ravi Sharma

Bits and Pieces

1. Find the frequency of elements in array

Method 1 : using reduce method of array, method 2 : using an object, 2. group items on the basis of age of given array of object, 3. program to c heck a string with balanced brackets., 4. find the pairs of array element for which sum is equal to given target value ( two sum problem), 5. find the missing number from unsorted array with o(n) complexity.

  • Create a variable sum = 1 which will store the missing number and a counter variable c = 2 .
  • Traverse the array from start to end.
  • Update the value of sum as sum = sum — array[i] + c and update c as c++ .
  • Print the missing number as a sum.

6. Find the missing number from sorted array with O(n) complexity

7. find the nth largest element in a sorted array, 8. remove duplicates from an array and return unique values in o(n) complexity., 9. print all duplicate elements of an array, 10. collect books from array of objects and return collection of books as an array.

I hope you have found this quick list of common JavaScript interview questions and answers useful. Thank you for reading!

Build Apps with reusable components, just like Lego

Bit ’s open-source tool helps 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

→ Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

→ Micro-Frontends

→ design system, → code-sharing and reuse, learn more:, how we build micro frontends, building micro-frontends to speed up and scale our web development process..

blog.bitsrc.io

How we Build a Component Design System

Building a design system with components to standardize and scale our ui development process., how to reuse react components across your projects, finally, you completed the task of creating a fantastic input field for the form in your app. you are happy with the…, 5 ways to build a react monorepo, build a production-grade react monorepo: from fast builds to code-sharing and dependencies., how to create a composable react app with bit, in this guide, you’ll learn how to build and deploy a full-blown composable react application with bit. building a….

Ravi Sharma

Written by Ravi Sharma

JavaScript Developer | https://www.youtube.com/channel/UC9MmyicGIveu0AId8OFAOmQ

More from Ravi Sharma and Bits and Pieces

Top 10 ReactJS Coding Interview Challenge For 2024

JavaScript in Plain English

Top 10 ReactJS Coding Interview Challenge For 2024

This article aims to provide an insightful exploration of coding challenges, and essential best practices for acing reactjs interviews. by….

Best-Practices for API Authorization

Chameera Dulanga

Best-Practices for API Authorization

4 best practices for api authorization.

Top 5 Node.js Features Every Developer Should Know

Danusha Navod

Top 5 Node.js Features Every Developer Should Know

Explore node.js worker threads, cluster, http2, streams api and repl.

Top 30 JavaScript Interview Questions and Answers for 2024

Top 30 JavaScript Interview Questions and Answers for 2024

Prepare for your next javascript interview with confidence, recommended from medium.

JavaScript Interview Preparation: let, const, and var

JavaScript Interview Preparation: let, const, and var

In this article, we’ll dive into the differences between let, const, and var in javascript and cover many important problems based on block….

React Coding Interview Questions & Answers with Coding Challenges

Shashipraba Perera

React Coding Interview Questions & Answers with Coding Challenges

Explain the concept of event delegation in javascript. why is it useful.

javascript problem solving questions and answers

General Coding Knowledge

javascript problem solving questions and answers

Stories to Help You Grow as a Software Developer

javascript problem solving questions and answers

Coding & Development

javascript problem solving questions and answers

Brandon Wohlwend

10 tricky interview Questions — Javascript

Hey there welcome back to another article about interview questions. today, we are dealing with 10 tricky javacript questions..

Polyfills for the call(), apply(), and bind() methods in JavaScript.

Shubham Gupta

Stackademic

Polyfills for the call(), apply(), and bind() methods in JavaScript.

The call(), apply() and bind() methods are used for function borrowing in javascript. it means that by using them, we can use the methods….

Explain Event Loop | Interview Questions

Sonika | @Walmart | FrontEnd Developer | 10 Years

Level Up Coding

Explain Event Loop | Interview Questions

Topic discussion:.

Open notebook with questions for JavaScript interview preparation

M Mainul Hasan

2024 Ultimate Guide to JavaScript Interview Questions and Answers

Master javascript for your next interview: from basics to advanced topics.

Text to speech

javascript problem solving questions and answers

Practice by framework

Javascript questions typescript supported, try these popular javascript questions, questions list.

  • Counter Warm Up Question Build a simple counter that increments whenever a button is clicked Difficulty Easy Available frameworks Users completed 10126 completed
  • Stack Implement a stack data structure containing the common stack methods Difficulty Easy Languages JS TS Users completed 3576 completed
  • Type Utilities Implement utilities to determine primitive variable types in JavaScript Difficulty Easy Languages JS TS Users completed 2996 completed
  • Cycle Implement a function that takes one or more values and returns a function that cycles through those values each time it is called Difficulty Easy Languages JS TS Users completed 717 completed
  • Insertion Sort Implement a function that performs an insertion sort Difficulty Easy Languages JS TS Users completed 1536 completed
  • Type Utilities II Implement utilities to determine non-primitive variable types in JavaScript Difficulty Easy Languages JS TS Users completed 1293 completed
  • Mortgage Calculator Build a calculator that computes the monthly mortgage for a loan Difficulty Easy Available frameworks Users completed 944 completed
  • Binary Search Implement a function that performs binary search on an array of numbers Difficulty Medium Languages JS TS Users completed 1681 completed
  • Breadth-first Search Implement a breadth-first search algorithm that traverses a directed graph in a breadth-first manner Difficulty Medium Languages JS TS Users completed 687 completed
  • Count By Implement a function that counts the number of times a value appears in an array based on a function or property name Difficulty Medium Languages JS TS Users completed 614 completed
  • Debounce Implement a function to limit how many times a function can be executed by delaying the execution of the function until after a specified time after its last execution attempt Difficulty Medium Languages JS TS Users completed 3077 completed
  • Depth-first Search Implement a depth-first search algorithm that traverses a directed graph in a depth-first manner Difficulty Medium Languages JS TS Users completed 693 completed
  • Heap Sort Implement a function that performs a heap sort Difficulty Medium Languages JS TS Users completed 234 completed
  • Queue Implement a queue data structure containing the common queue methods Difficulty Medium Languages JS TS Users completed 766 completed
  • Tabs Build a tabs component that displays a list of tab elements and one associated panel of content at a time Difficulty Medium Available frameworks Users completed 1553 completed
  • Classnames Implement a function that conditionally joins CSS class names together Difficulty Medium Languages CSS JS TS Users completed 1056 completed
  • Event Emitter Implement a class that can subscribe to and emit events that trigger attached callback functions Difficulty Medium Languages JS TS Users completed 461 completed
  • Flatten Implement a function that recursively flattens an array into a single level deep Difficulty Medium Languages JS TS Users completed 3172 completed
  • Merge Sort Implement a function that performs a recursive merge sort Difficulty Medium Languages JS TS Users completed 370 completed
  • Promise.all Implement the Promise.all() function that resolves to an array of results if all the input elements are resolved or rejects otherwise Difficulty Medium Languages JS TS Users completed 1962 completed
  • Quick Sort Implement a function that performs a recursive quick sort Difficulty Medium Languages JS TS Users completed 292 completed
  • Todo List Build a Todo list that lets users add new tasks and delete existing tasks Difficulty Medium Available frameworks Users completed 2439 completed
  • Topological Sort Implement a function that performs a topological sort Difficulty Medium Languages JS TS Users completed 114 completed
  • Traffic Light Build a traffic light where the lights switch from green to yellow to red after predetermined intervals and loop indefinitely Difficulty Medium Available frameworks Users completed 826 completed
  • Deep Clone Implement a function that performs a deep copy of a value Difficulty Medium Languages JS TS Users completed 1194 completed
  • Digital Clock Build a 7-segment digital clock that shows the current time Difficulty Medium Available frameworks Users completed 512 completed
  • Job Board Build a job board that displays the latest job postings from Hacker News Difficulty Medium Available frameworks Users completed 591 completed
  • Clamp Implement a function to clamp a number within the inclusive lower and upper bounds Difficulty Easy Languages JS TS Users completed 2355 completed
  • Function Length Implement a function that returns the number of parameters expected by a function Difficulty Easy Languages JS TS Users completed 1973 completed
  • Make Counter Implement a function that accepts an integer value and returns a function that can be repeatedly called to return increasing values Difficulty Easy Languages JS TS Users completed 1753 completed
  • Number of Arguments Implement a function that returns the number of arguments it was called with Difficulty Easy Languages JS TS Users completed 1703 completed
  • Sleep Implement a function that pauses for a specified duration before resuming execution Difficulty Easy Languages JS TS Users completed 1698 completed
  • Array.prototype.square Implement a custom Array.prototype.square() method that squares the values in an array Difficulty Easy Languages JS TS Users completed 2592 completed
  • Cancellable Interval Implement a function that acts like setInterval but returns a function to cancel the interval Difficulty Easy Languages JS TS Users completed 1336 completed
  • Cancellable Timeout Implement a function that acts like setTimeout but returns a function to cancel the pending callback Difficulty Easy Languages JS TS Users completed 1234 completed
  • Chunk Implement a function that creates an array of elements split into smaller groups of a specified size Difficulty Easy Languages JS TS Users completed 1509 completed
  • Compact Implement a function that creates an array with all falsey values removed Difficulty Easy Languages JS TS Users completed 1452 completed
  • Difference Implement a function that finds the difference in values between arrays Difficulty Easy Languages JS TS Users completed 1231 completed
  • Drop Right While Implement a function that excludes elements from the end of an array until the predicate returns false Difficulty Easy Languages JS TS Users completed 953 completed
  • Drop While Implement a function that excludes elements from the beginning of an array until the predicate returns false Difficulty Easy Languages JS TS Users completed 869 completed
  • Fill Implement a function that fills an array with values within specified indices Difficulty Easy Languages JS TS Users completed 774 completed
  • Find Index Implement a function that returns the index of the first element in the array that satisfies the provided testing function Difficulty Easy Languages JS TS Users completed 785 completed
  • Find Last Index Implement a function that returns the index of the last element in the array that satisfies the provided testing function Difficulty Easy Languages JS TS Users completed 623 completed
  • From Pairs Implement a function that returns an object composed from key-value pairs Difficulty Easy Languages JS TS Users completed 939 completed
  • Function.prototype.apply Implement the Function.prototype.apply() function that calls the function with a given `this` value and arguments as an array Difficulty Easy Languages JS TS Users completed 544 completed
  • Function.prototype.call Implement the Function.prototype.call() function that calls the function with a given `this` value and provided arguments Difficulty Easy Languages JS TS Users completed 510 completed
  • Get Implement a function to safely access deeply-nested properties in JavaScript objects Difficulty Easy Languages JS TS Users completed 2032 completed
  • In Range Implement a function to check if a number falls between two numbers Difficulty Easy Languages JS TS Users completed 722 completed
  • Intersection Implement a function that computes the intersection of arrays, returning a new array containing unique values present in all given arrays Difficulty Easy Languages JS TS Users completed 462 completed
  • Object Map Implement a function to transform values within an object Difficulty Easy Languages JS TS Users completed 404 completed
  • Once Implement a function that accepts a callback and restricts its invocation to at most once Difficulty Easy Languages JS TS Users completed 1039 completed
  • Promise.reject Implement a function to return a Promise object rejected with a reason Difficulty Easy Languages JS TS Users completed 651 completed
  • Selection Sort Implement a function that performs a selection sort Difficulty Easy Languages JS TS Users completed 889 completed
  • Singleton Implement a Singleton class that ensures a class has only one instance while providing a global point of access to that instance Difficulty Easy Languages JS TS Users completed 204 completed
  • Unique Array Implement a function to remove all duplicate values from an array Difficulty Easy Languages JS TS Users completed 1804 completed
  • Accordion Build an accordion component that a displays a list of vertically stacked sections with each containing a title and content snippet Difficulty Easy Available frameworks Users completed 1366 completed
  • Array.prototype.at Implement the Array.prototype.at() method Difficulty Easy Languages JS TS Users completed 421 completed
  • Array.prototype.filter Implement the Array.prototype.filter() method Difficulty Easy Languages JS TS Users completed 2253 completed
  • Array.prototype.map Implement the Array.prototype.map() method Difficulty Easy Languages JS TS Users completed 1710 completed
  • Array.prototype.reduce Implement the Array.prototype.reduce() method Difficulty Easy Languages JS TS Users completed 1372 completed
  • Compose Implement a function that takes multiple functions as arguments and returns a new function that applies those functions in reverse Difficulty Easy Languages JS TS Users completed 335 completed
  • Flight Booker Build a component that books a flight for specified dates Difficulty Easy Available frameworks Users completed 693 completed
  • Function.prototype.bind Implement the Function.prototype.bind() function that creates a new function with the `this` keyword set to a provided value Difficulty Easy Languages JS TS Users completed 1261 completed
  • Generate Table Generate a table of numbers given the rows and columns Difficulty Easy Available frameworks Users completed 697 completed
  • jQuery.css Implement a jQuery-like function that sets the style of a DOM element Difficulty Easy Languages HTML CSS JS TS Users completed 1282 completed
  • Progress Bar Build a progress bar component that shows the percentage completion of an operation Difficulty Easy Available frameworks Users completed 1227 completed
  • Progress Bars Build a list of progress bars that fill up gradually when they are added to the page Difficulty Easy Available frameworks Users completed 667 completed
  • Promise.race Implement the Promise.race() function that resolves or rejects when any of the input elements are resolved or rejected Difficulty Easy Languages JS TS Users completed 844 completed
  • Size Implement a function that returns the size of collection Difficulty Easy Languages JS TS Users completed 282 completed
  • Sum Implement a function that sums numbers by accepting a number and allows for repeated calling with more numbers until it is not called with any number Difficulty Easy Languages JS TS Users completed 984 completed
  • Temperature Converter Build a temperature converter widget that converts temperature values between Celsius and Fahrenheit Difficulty Easy Available frameworks Users completed 1053 completed
  • Make Counter II Implement a function that returns a counter object with methods to retrieve and manipulate the value Difficulty Medium Languages JS TS Users completed 551 completed
  • Array.prototype.concat Implement the Array.prototype.concat() method Difficulty Medium Languages JS TS Users completed 286 completed
  • Curry Implement a function that transforms a function that takes multiple arguments into a function that can be repeatedly called with only one argument at a time Difficulty Medium Languages JS TS Users completed 1689 completed
  • Group By Implement a function that groups values in an array based on a function or property name Difficulty Medium Languages JS TS Users completed 270 completed
  • Intersection By Implement a function that returns an array of unique values that are included in all given arrays based on a provided iteratee function Difficulty Medium Languages JS TS Users completed 214 completed
  • Intersection With Computes the intersection of arrays using a custom comparator function to determine equality between elements Difficulty Medium Languages JS TS Users completed 168 completed
  • Is Empty Implement a function to check if a value is an empty object, collection, map, or set Difficulty Medium Languages JS TS Users completed 326 completed
  • Limit Implement a function that accepts a callback and restricts its invocation to at most N times Difficulty Medium Languages JS TS Users completed 554 completed
  • Promise Merge Implement a function to merge the results of two promises into a single value Difficulty Medium Languages JS TS Users completed 345 completed
  • Promise Timeout Implement a function that resolves a promise if it is fulfilled within a timeout period and rejects otherwise Difficulty Medium Languages JS TS Users completed 359 completed
  • Promise.resolve Implement a function to resolve a given value to a Promise Difficulty Medium Languages JS TS Users completed 303 completed
  • Promisify Implement a function that takes a function following the common error-first callback style and returns a version that returns promises Difficulty Medium Languages JS TS Users completed 324 completed
  • Promisify II Implement a promisify function that allows the original function to override the return value Difficulty Medium Languages JS TS Users completed 125 completed
  • Throttle Implement a function to control the execution of a function by limiting how many times it can execute over time Difficulty Medium Languages JS TS Users completed 1318 completed
  • Turtle Implement a Turtle class that moves a turtle on a 2D plane Difficulty Medium Languages JS TS Users completed 128 completed
  • Accordion II Build an accessible accordion component that has the right ARIA roles, states, and properties Difficulty Medium Available frameworks Users completed 285 completed
  • Accordion III Build a fully accessible accordion component that has keyboard support according to ARIA specifications Difficulty Medium Available frameworks Users completed 147 completed
  • Analog Clock Build an analog clock where the hands update and move like a real clock Difficulty Medium Available frameworks Users completed 226 completed
  • Camel Case Keys Implement a function to convert all the keys in an object to camel case Difficulty Medium Languages JS TS Users completed 467 completed
  • Compact II Implement a function that returns an object with all falsey values removed Difficulty Medium Languages JS TS Users completed 100 completed
  • Curry II Implement a function that transforms a function that takes multiple arguments into a function that can be repeatedly called with any number of arguments Difficulty Medium Languages JS TS Users completed 533 completed
  • Data Merging Implement a function to merge rows of data from the same user Difficulty Medium Languages JS TS Users completed 136 completed
  • Debounce II Implement a debounce function that comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke them Difficulty Medium Languages JS TS Users completed 437 completed
  • Event Emitter II Implement a class that can subscribe to and emit events that trigger attached callback functions. Subscription objects are returned and can unsubscribe itself Difficulty Medium Languages JS TS Users completed 272 completed
  • getElementsByTagName Implement a function to get all DOM elements that match a tag Difficulty Medium Languages HTML JS TS Users completed 843 completed
  • Grid Lights Build a grid of lights where the lights deactivate in the reverse order they were activated Difficulty Medium Available frameworks Users completed 351 completed
  • HTML Serializer Implement a function to serialize an object into an HTML string with indentation Difficulty Medium Languages HTML JS TS Users completed 204 completed
  • Identical DOM Trees Implement a function to determine if two DOM trees are the same Difficulty Medium Languages HTML JS TS Users completed 440 completed
  • jQuery Class Manipulation Implement a set of jQuery-like functions that manipulates classes on a DOM element Difficulty Medium Languages HTML CSS JS TS Users completed 326 completed
  • JSON.stringify Implement a function that converts a JavaScript value into a JSON string Difficulty Medium Languages JS TS Users completed 262 completed
  • Like Button Build a Like button that changes appearance based on the states Difficulty Medium Available frameworks Users completed 414 completed
  • List Format Implement a function that formats a list of items into a single readable string Difficulty Medium Languages JS TS Users completed 769 completed
  • Map Async Implement a function that maps an array of items with an asynchronous mapping function Difficulty Medium Languages JS TS Users completed 105 completed
  • Memoize Implement a function that returns a memoized version of a function which accepts a single argument Difficulty Medium Languages JS TS Users completed 164 completed
  • Progress Bars II Build a list of progress bars that fill up gradually in sequence, one at a time Difficulty Medium Available frameworks Users completed 221 completed
  • Promise.allSettled Implement the Promise.allSettled() function that resolves to an array of outcomes when all the input elements are either resolved or rejected Difficulty Medium Languages JS TS Users completed 526 completed
  • Promise.any Implement the Promise.any() function that resolves when any of the input elements are resolved Difficulty Medium Languages JS TS Users completed 677 completed
  • Resumable Interval Implement a function that creates a resumable interval object Difficulty Medium Languages JS TS Users completed 98 completed
  • Squash Object Implement a function that returns a new object after squashing the input object into a single level of depth Difficulty Medium Languages JS TS Users completed 347 completed
  • Star Rating Build a star rating component that shows a row of star icons for users to select the number of filled stars corresponding to the rating Difficulty Medium Available frameworks Users completed 883 completed
  • Tabs II Build a semi-accessible tabs component that has the right ARIA roles, states, and properties Difficulty Medium Available frameworks Users completed 145 completed
  • Tabs III Build a fully accessible tabs component that has keyboard support according to ARIA specifications Difficulty Medium Available frameworks Users completed 92 completed
  • Text Search Implement a function to highlight text if a searched term appears within it Difficulty Medium Languages HTML JS TS Users completed 435 completed
  • Deep Equal Implement a function that determines if two values are equal Difficulty Medium Languages JS TS Users completed 669 completed
  • Deep Map Implement a function to recursively transform values Difficulty Medium Languages JS TS Users completed 77 completed
  • getElementsByClassName Implement a function to get all DOM elements that contain the specified classes Difficulty Medium Languages HTML CSS JS TS Users completed 405 completed
  • Map Async Limit Implement a function that maps an array of items with an asynchronous mapping function while not exceeding the concurrency limit Difficulty Medium Languages JS TS Users completed 53 completed
  • Progress Bars III Build a list of progress bars that fill up gradually concurrently, up to a limit of 3 Difficulty Medium Available frameworks Users completed 143 completed
  • Text Search II Implement a function to highlight text if searched terms appear within it Difficulty Medium Languages HTML JS TS Users completed 131 completed
  • Tic-tac-toe Build a tic-tac-toe game that is playable by two players Difficulty Medium Available frameworks Users completed 219 completed
  • Deep Merge Implement a function that merges two objects together Difficulty Medium Languages JS TS Users completed 67 completed
  • Deep Omit Implement a function that removes specified keys and their corresponding values from an object, including nested objects or arrays Difficulty Medium Languages JS TS Users completed 61 completed
  • Memoize II Implement a function that returns a memoized version of a function which accepts any number of arguments Difficulty Medium Languages JS TS Users completed 110 completed
  • Signup Form Build a signup form that does validation on user details and submits to a back end API Difficulty Medium Available frameworks Users completed 320 completed
  • Stopwatch Build a stopwatch widget that can measure how much time has passed Difficulty Medium Available frameworks Users completed 182 completed
  • Transfer List Build a component that allows transferring of items between two lists Difficulty Medium Available frameworks Users completed 190 completed
  • Undoable Counter Build a counter with a history of the values and ability to undo/redo actions Difficulty Medium Available frameworks Users completed 156 completed
  • Whack-A-Mole Build a popular arcade game where players attempt to hit moles as they pop up from holes in a board Difficulty Medium Available frameworks Users completed 70 completed
  • Memory Game Build a memory game where the player needs to match pairs of cards Difficulty Medium Available frameworks Users completed 72 completed
  • Curry III Implement a function which transforms a function which takes variadic arguments into a function that can be repeatedly called with any number of arguments Difficulty Hard Languages JS TS Users completed 110 completed
  • Classnames II Implement a function that conditionally joins CSS class names together and also handles de-duplication and function values Difficulty Hard Languages CSS JS TS Users completed 31 completed
  • Progress Bars IV Build a list of progress bars that fill up gradually concurrently, up to a limit of 3 and allows for pausing and resuming Difficulty Hard Available frameworks Users completed 76 completed
  • Backbone Model Implement a class resembling Backbone.Model which allows storing of attributes/values and responding to changes in specific attribute values Difficulty Hard Languages JS TS Users completed 14 completed
  • Data Selection Implement a function to filter rows of data matching a specified requirement Difficulty Hard Languages JS TS Users completed 223 completed
  • Table of Contents Implement a function to construct a table of contents from an HTML document Difficulty Hard Languages HTML JS TS Users completed 133 completed
  • Tic-tac-toe II Build an N x N tic-tac-toe game that requires M consecutive marks to win Difficulty Hard Available frameworks Users completed 47 completed
  • Transfer List II Build a component that allows transferring of items between two lists, bulk selection/unselection of items, and adding of new items Difficulty Hard Available frameworks Users completed 52 completed
  • Deep Clone II Implement a function that performs a deep copy of a value, but also handles circular references Difficulty Hard Languages JS TS Users completed 74 completed
  • JSON.stringify II Implement a function that converts a JavaScript value into a JSON string Difficulty Hard Languages JS TS Users completed 25 completed
  • Wordle Build Wordle, the word-guessing game that took the world by storm Difficulty Hard Available frameworks Users completed 35 completed

10 Days of Javascript

Calender

Improve your Javascript basics.

IMAGES

  1. Assignment 1

    javascript problem solving questions and answers

  2. JavaScript Problem Solving & Algorithms Guide

    javascript problem solving questions and answers

  3. How can I solve this javascript math problem?

    javascript problem solving questions and answers

  4. Problem Solving with JavaScript. Problem solving is a crucial skill of

    javascript problem solving questions and answers

  5. JavaScript Problem Solving, Problem: 02. Variable.js Problem

    javascript problem solving questions and answers

  6. Problem Solving with Code

    javascript problem solving questions and answers

VIDEO

  1. javascript problem solving question #7 @CodeHelp

  2. Day 9 / 75 Javascript Problem Solving Question /#9/#javascript #css @CodeHelp

  3. Can You Solve This JavaScript Problem?

  4. Day 10 / 75: Javascript Problem Solving Question: #10 #javascript @CodeHelp #html

  5. Problem Solving #15 Repeater Problem

  6. Daily JavaScript Problem Solving

COMMENTS

  1. 25+ JavaScript Coding Interview Questions (SOLVED with CODE)

    FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time. Check 25+ JavaScript Coding Interview Questions (SOLVED with CODE) and Land Your Next Six-Figure Job Offer! 100% Tech Interview Success!

  2. JavaScript Exercises, Practice Questions and Solutions

    These JavaScript practice questions are ideal for beginners and experienced developers. So, to test your skills, go through these JavaScript exercises with solutions. A step-by-step JavaScript practice guide for beginner to advanced level. Benefits of Practice JavaScript Interactive Quizzes: Engage in hands-on JavaScript quizzes.

  3. Top 50 JavaScript Interview Questions With Example Answers

    Common JavaScript Interview Questions What are the different data types in JavaScript? What is hoisting in JavaScript? What is the difference between null and undefined? What are closures in JavaScript? What is a callback function in JavaScript? What are promises in JavaScript? What is the purpose of the setTimeout () function in Javascript?

  4. Top 50 JavaScript coding Interview Questions and Answers

    The basic JavaScript coding interview questions are: 1. Write a JavaScript function to calculate the sum of two numbers. When managers ask this question, they are looking for the candidate's basic understanding of JavaScript. They assess their understanding of basic syntax along with problem-solving skills.

  5. JavaScript Coding Interview Practice

    Interview Question 1: How to Get Passengers' Names. Let's get the passengers' names as requested. The first solution is through a 'for loop' method. So we first need to use an empty array to push the passengers' names right inside it at the end of the loop.

  6. JavaScript Interview Questions and Answers

    JavaScript Interview Questions and Answers Read Courses JavaScript (JS) is the most popular lightweight scripting and compiled programming language. It was developed by Brendan Eich in 1995. It is well-known as a scripting language for web pages, mobile apps, web servers, and many more.

  7. Free Javascript challenges online

    3.647.847 challenges solved Most popular challenges Reassign a value to a variable Get nth character of string Comparison operators, strict equality Check if a number is a whole number Sum two numbers Most failed challenges Pop the balloons Cursor enters and leaves element Input filter list

  8. 37 Essential JavaScript Interview Questions

    Toptal sourced essential questions that the best JavaScript developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback. Hire a Top JavaScript Developer Now

  9. 30 JavaScript Coding Interview Questions

    When designing interview questions for mid-level JavaScript developers, you should prepare challenges to test the understanding of advanced JavaScript concepts and problem-solving skills. Some areas that should be considered for evaluation include functional programming, asynchronous programming, promises, working with APIs and advanced ...

  10. Part 1-100 Advanced JavaScript Interview Questions with Answers and

    To truly evaluate a candidate's expertise in advanced JavaScript concepts, it's important to ask thought-provoking questions that delve into their problem-solving skills. In this article, we present ten advanced JavaScript interview questions accompanied by detailed answers and code samples.

  11. Front End Interview JavaScript Questions

    How to Prepare for JavaScript Coding Interviews. Be familiar with HTML, CSS, JavaScript, and DOM concepts by referring to the "Important Concepts" below. The Quiz section can also be a good start since you might be asked on these concepts in the form of quiz questions during coding. Pick a study plan and practice the JavaScript coding questions ...

  12. JavaScript Interview Questions and Answers (2024)

    JavaScript Interview Questions Last Updated: Jan 03, 2024 Download PDF Download PDF Your requested download is ready! Click here to download. Powered by Certificate included About the Speaker What will you Learn? I wish to receive further updates and confirmation via whatsapp Register Now Learn via Video Course

  13. Solve common problems in your JavaScript code

    const myNumber = 0; With Objects, however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. For example: js const myObject = { name: "Chris", age: 38, }; Basic definitions What is JavaScript?

  14. JavaScript Exercises, Practice, Solution

    Happy Coding! Latest Exercises : Object Oriented Programming JavaScript Error Handling JavaScript Event Handling List of JavaScript Exercises : JavaScript Basic [ 150 Exercises with Solution ] JavaScript Fundamental (ES6 version) Part-I [ 150 Exercises with Solution ] JavaScript Fundamental (ES6 version) Part-II [ 116 Exercises with Solution ]

  15. 2,500+ JavaScript Practice Challenges // Edabit

    In the Code tab above you'll see a starter function that looks like this: function hello () { } All you have to do is type return "hello edabit.com" between the curly braces { } and then click the Check button. If you did this correctly, the button will turn red and … language_fundamentals strings Very Easy Return the Sum of Two Numbers

  16. 65 JavaScript Interview Questions & Answers to Prepare For (Beg to Adv)

    Keep in mind that many JavaScript interview questions are open-ended and don't have one correct answer. When you're interviewing a potential candidate, make sure to focus on evaluating not only their technical expertise but also on their thought process and problem-solving skills. You can also explore HireAI to skip the line and:

  17. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies. ... Interview. Store Study Plan. See all. Array 1571. String 672. Hash Table 558. Dynamic Programming 483. Math ...

  18. GitHub

    List of 1000 JavaScript Interview Questions. Contribute to sudheerj/javascript-interview-questions development by creating an account on GitHub.

  19. 10 Common JavaScript Interview Questions (and Answers)

    Method 1: Using Reduce method of array Method 2: Using an Object 2. Group items on the basis of age of given array of object 3. Program to c heck a string with balanced brackets. 4. Find the pairs of array element for which sum is equal to given target value ( Two Sum Problem) 5. Find the missing number from unsorted array with O (n) complexity

  20. Practice Top JavaScript and TypeScript Front End Interview Questions

    JavaScript questions TypeScript supported 190+ JavaScript and TypeScript interview questions, from implementing common library APIs, utility functions, algorithms, to building UI components and more. Try these popular JavaScript questions. Array.prototype.concat Implement the Array.prototype.concat() method.

  21. Solve Tutorials

    Improve your Javascript basics. Join 10 Days of Javascript Join over 16 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  22. 10 JavaScript Coding Interview Questions Solve With Code

    Q-1: Write a function that would allow you to do this. You can create a closure to keep the value of a even after the inner function is returned. The inner function that is being returned is ...

  23. 10 Common JavaScript Interview Questions and How to Answer Them

    This question assesses your knowledge of variable declaration in JavaScript. Explain that "let" and "const" are block-scoped variables, while "var" is function-scoped. Emphasize that ...