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

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

problem solving questions for javascript

JavaScript Coding Interview Practice – Sample Interview Questions and Solutions

Damla Erkiner

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

Level up your JavaScript skills with 10 coding challenges

Level up your JavaScript Skills with Coding Challenges

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.

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript exercises.

You can test your JavaScript skills with W3Schools' Exercises.

We have gathered a variety of JavaScript exercises (with answers) for each JavaScript Chapter.

Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start JavaScript Exercises

Start JavaScript Exercises ❯

If you don't know JavaScript, we suggest that you read our JavaScript Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Top 50 JavaScript Interview Questions With Example Answers

problem solving questions for javascript

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 automatic conversion of a value from one type to another. In JavaScript, this conversion follows a priority order that typically begins with strings, then numbers, and finally booleans. If you try to add a string to a number, JavaScript will implicitly coerce the number to a string before performing the addition operation because strings have the highest priority in type coercion.

For example, when you combine the number 5 with the string '10' using the addition operator, the result is the string '510' . This occurs because JavaScript will implicitly convert the number 5 to a string following the priority of coercion, and then concatenate it to the string '10' .

A JavaScript code snippet

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.

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
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

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?

CodeGuppy Logo

  • JavaScript Coding Challenges for Beginners

Login to your Account

Forgot Password?

Mastering these coding challenges may not get you a job at Google... but you'll be one step closer to building your own JavaScript game at codeguppy.com

YouTube Channel

After you read this article, please remember to check out also the “Coding Adventures” YouTube channel. You’ll find there a series of fun and engaging coding lessons and cool projects.

Channel main page Coding lessons playlist Coding projects playlist

The coding challenges in this article are intended for code newbies, therefore the solutions are implemented using only simple / classical programming elements. Each solution is acompanied by an online link that helps you quickly run it in a code playground.

If you prefer to open all solutions in a single, unified coding playgroud please open the 50 Coding Challenges project.

The code is making use of the codeguppy specific function println() to print the results. If you want to run these solutions outside CodeGuppy, just replace println() with console.log() then run them using your browser console tool or node.js.

Coding challenge #1: Print numbers from 1 to 10

Edit in coding playground

Coding challenge #2: Print the odd numbers less than 100

Coding challenge #3: print the multiplication table with 7, coding challenge #4: print all the multiplication tables with numbers from 1 to 10, coding challenge #5: calculate the sum of numbers from 1 to 10, coding challenge #6: calculate 10, coding challenge #7: calculate the sum of odd numbers greater than 10 and less than 30, coding challenge #8: create a function that will convert from celsius to fahrenheit, coding challenge #9: create a function that will convert from fahrenheit to celsius, coding challenge #10: calculate the sum of numbers in an array of numbers, coding challenge #11: calculate the average of the numbers in an array of numbers, coding challenge #12: create a function that receives an array of numbers and returns an array containing only the positive numbers, coding challenge #13: find the maximum number in an array of numbers, coding challenge #14: print the first 10 fibonacci numbers without recursion, coding challenge #15: create a function that will find the nth fibonacci number using recursion, coding challenge #16: create a function that will return a boolean specifying if a number is prime, coding challenge #17: calculate the sum of digits of a positive integer number, coding challenge #18: print the first 100 prime numbers, coding challenge #19: create a function that will return in an array the first "nprimes" prime numbers greater than a particular number "startat", coding challenge #20: rotate an array to the left 1 position, coding challenge #21: rotate an array to the right 1 position, coding challenge #22: reverse an array, coding challenge #23: reverse a string, coding challenge #24: create a function that will merge two arrays and return the result as a new array, coding challenge #25: create a function that will receive two arrays of numbers as arguments and return an array composed of all the numbers that are either in the first array or second array but not in both, coding challenge #26: create a function that will receive two arrays and will return an array with elements that are in the first array but not in the second, coding challenge #27: create a function that will receive an array of numbers as argument and will return a new array with distinct elements, coding challenge #28: calculate the sum of first 100 prime numbers, coding challenge #29: print the distance between the first 100 prime numbers, coding challenge #30-a: create a function that will add two positive numbers of indefinite size. the numbers are received as strings and the result should be also provided as string., coding challenge #30-b: create a function that will add two positive numbers of indefinite size. the numbers are received as strings and the result should be also provided as string., coding challenge #31a. create a function that will return the number of words in a text, coding challenge #31b. create a function that will return the number of words in a text, coding challenge #32. create a function that will capitalize the first letter of each word in a text, coding challenge #33. calculate the sum of numbers received in a comma delimited string, coding challenge #34. create a function that will return an array with words inside a text, coding challenge #35. create a function to convert a csv text to a “bi-dimensional” array, coding challenge #36. create a function that converts a string to an array of characters, coding challenge #37. create a function that will convert a string in an array containing the ascii codes of each character, coding challenge #38. create a function that will convert an array containing ascii codes in a string, coding challenge #39. implement the caesar cypher, coding challenge #40. implement the bubble sort algorithm for an array of numbers, coding challenge #41. create a function to calculate the distance between two points defined by their x, y coordinates, coding challenge #42. create a function that will return a boolean value indicating if two circles defined by center coordinates and radius are intersecting, coding challenge 43. create a function that will receive a bi-dimensional array as argument and a number and will extract as a unidimensional array the column specified by the number, coding challenge #44. create a function that will convert a string containing a binary number into a number, coding challenge #45. create a function to calculate the sum of all the numbers in a jagged array (array contains numbers or other arrays of numbers on an unlimited number of levels), coding challenge #46-a. find the maximum number in a jagged array of numbers or array of numbers, coding challenge #46-b. find the maximum number in a jagged array of numbers or array of numbers, coding challenge #47. deep copy a jagged array with numbers or other arrays in a new array, coding challenge #48. create a function to return the longest word(s) in a string, coding challenge #49. shuffle an array of strings, coding challenge #50. create a function that will receive n as argument and return an array of n unique random numbers from 1 to n., coding challenge #51. find the frequency of characters inside a string. return the result as an array of objects. each object has 2 fields: character and number of occurrences., coding challenge #52. calculate fibonacci(500) with high precision (all digits), coding challenge #53. calculate 70 with high precision (all digits).

  • About codeguppy

problem solving questions for javascript

Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.

  • 7 Educational Tools That You Can Code Yourself in JavaScript
  • 8 Computer Science Algorithms You Can Implement in JavaScript
  • JavaScript is like Python
  • Sending Coding Greeting Cards: A Unique Way to Inspire Young Minds
  • Embracing Allman Style in Coding Education: A JavaScript Perspective
  • Coding Books for Kids: Expanding Your Digital Horizons
  • How Many Bits Do You Need to Store the Number 34,234,230,950,425?
  • How to Write Beautiful JavaScript Code
  • Why Are There 8 Bits in a Byte?
  • How Kids Learned Programming in the 80s?
  • Raspberry Pi 400 and Orange Pi 800 - A Computer Inside of a Keyboard!
  • Should I Start Coding with Scratch, Python, or JavaScript?
  • Make a retro game with custom sprites using JavaScript
  • How to implement collision detection between two circles using p5.js?
  • How to calculate the distance between two points using JavaScript and p5.js?
  • Why 0.1 + 0.2 is not 0.3 in JavaScript?
  • 10 Coding Projects for Middle and High School Students
  • Building a Raspberry Pi Paper Computer in Your Coding Club
  • Computer Science Curriculum for teaching JavaScript
  • From 80's BASIC to JavaScript
  • What is ASCII?
  • Importance of code indentation
  • How to write clean code?
  • Explaining binary numbers using light bulbs
  • Charles Babbage facts for kids
  • Avoid these top 10 coding mistakes
  • About ASCII and Unicode
  • 12 questions answered about coding
  • 10 myths about coding
  • Top 5 free coding platforms for kids
  • p5.js in the classroom
  • How to organize a coding club for kids?
  • History of programming languages
  • About coordinate systems
  • Binary system
  • Best coding websites for kids
  • Ada Lovelace facts for kids
  • About early computers
  • 20 ways to improve your coding skills
  • Coding Resources for Teachers
  • Easy Games to Code for Beginners
  • Exploring the World of Drawing with code
  • High School Computer Science Curriculum in PowerPoint format
  • JavaScript and Game Programming Curriculum
  • JavaScript Curriculum - A great Teaching Resource
  • What is recursion in JavaScript?
  • What is data compression?
  • What is a coding style guide?
  • Transitioning kids from block-based coding to text-based coding
  • Top 10 javascript coding questions you were afraid to ask
  • Scratch vs Python vs JavaScript
  • Recursion in JavaScript - Practical examples
  • Organize a game jam in your coding club
  • How to select a coding platform for your classroom?
  • How JavaScript got its name?
  • Hexadecimal system
  • Can you solve these riddles using JavaScript?
  • Coding projects for middle and high school students
  • Teaching with p5.js
  • Python or JavaScript. What's the best programming language to learn first?
  • The first million primes
  • Coding hints V: Other coding hints
  • Coding hints IV: JavaScript Game Development with codeguppy.com
  • Coding hints III: User Input
  • Coding hints II: Drawing on canvas using JavaScript
  • Coding hints I: JavaScript Syntax
  • Flood fill in JavaScript – Recursion or no recursion?
  • Calculate PI in JavaScript ... by throwing darts
  • Calculate PI by measuring the area of a circle in JavaScript
  • Build a fantasy CPU emulator in JavaScript
  • Calculate 70! in JavaScript
  • JavaScript Modulo and the Caesar Cipher
  • Teach Coding and Computer Science at Your School
  • Porting programs between Khan Academy and codeguppy.com
  • Free Coding Platforms
  • Using external images and sprites
  • codeguppy for p5.js users
  • Best coding website for kids
  • Type-in programs
  • JavaScript for Kids
  • Hour of Code

What Users say?

CodeGuppy allows me to create my own games that I can share with my friends.

I was always interested to see how the classic games such as Pong and Breakout were made. CodeGuppy has tutorials for these games as well as many others.

CodeGuppy is the best coding site on the entire web.

problem solving questions for javascript

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 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.

7 Node.js Design Patterns Every Developer Should Know

Danusha Navod

7 Node.js Design Patterns Every Developer Should Know

Explore the facade, adapter, singleton, prototype, builder, proxy and factory for modern software design..

Top 10 Tools Every React Developer Needs in 2024

Ashan Fernando

Top 10 Tools Every React Developer Needs in 2024

Enhancing efficiency and creativity in the react ecosystem using these highly effective tools.

Top 40 ReactJS Interview Questions and Answers for 2024

Stackademic

Top 40 ReactJS Interview Questions and Answers for 2024

Reactjs has become a cornerstone of modern web development, with its component-based architecture and efficient rendering making it a go-to…, recommended from medium.

A JavaScript Interview Question That 90% of People Get Wrong

Awwwesssooooome

JavaScript in Plain English

A JavaScript Interview Question That 90% of People Get Wrong

Let’s take a look at the question first:.

problem solving questions for javascript

General Coding Knowledge

problem solving questions for javascript

Stories to Help You Grow as a Software Developer

problem solving questions for javascript

Coding & Development

problem solving questions for javascript

Mastering the Interview: 20 ReactJS Interview Questions for Senior Frontend Developers

As a seasoned frontend developer specializing in reactjs, landing a senior position requires more than just expertise in the framework….

Interview Concepts on JavaScript Functions

Prakash Pun

Interview Concepts on JavaScript Functions

This article is based on the guide i am currently working on that can help you prepare for javascript interview concepts. the initial two….

53 JavaScript Frontend Interview Questions

53 JavaScript Frontend Interview Questions

Introduction.

Razorpay Interview Experience — Full-Time -Frontend Developer Role 2023

Anjali Bhosale

Razorpay Interview Experience — Full-Time -Frontend Developer Role 2023

Hello folks, i had the opportunity to interview recently at razorpay for the software development engineer 2— frontend developer role….

Text to speech

List of Problems

This page contains the list of all programming problems in no particular order. If you have solved a problem, its row turns green. Click on any problem to start coding!

10 Days of Javascript

Calender

Improve your Javascript basics.

Cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

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.

  • Guidelines to Write Experiences
  • Write Interview Experience
  • Write Work Experience
  • Write Admission Experience
  • Write Campus Experience
  • Write Engineering Experience
  • Write Coaching Experience
  • Write Professional Degree Experience
  • Write Govt. Exam Experiences
  • JP Morgan Interview Experience Through Code For Good(CFG)
  • Contest Experiences | My first Leetcode Coding Contest Experince
  • Contest Experience - How to begin Coding on GeeksforGeeks
  • What coding habits improve timing in coding contest?
  • How to Write Coding Contest Experiences on GeeksForGeeks
  • Contest Experiences: Beginner's Guide to Coding Contests
  • Contest Experience - My First Coding Contest
  • Contest Experiences | GeeksforGeeks Weekly Coding Contest
  • Most Popular Weekly Coding Contest Platforms
  • My Code Frenzy Experience: Challenging Rounds and a Valuable Learning Journey
  • How to use Chat-GPT to solve Coding Problems?
  • Can ChatGPT be used to solve Competitive Coding Problems?
  • Contest Experience - GeeksForGeeks Weekly Coding Contest 119
  • Contest Experience - Google Summer of Code (GSoC)
  • Contest Experiences | Geeksforgeeks: Bi-Wizard School Coding Tournament 16.0
  • Contest Experiences | Geeksforgeeks GFG Weekly Coding Contest - 105
  • Google's Coding Competitions You Can Consider
  • Code India Code - Challenge Your Coding Skills with GeeksforGeeks
  • Contest Experiences | Bi-Wizard School Coding Tournament 17.0

My Journey of Learning Problem-Solving Skills through Coding Contests

I still remember the day I gave my first coding contest because I learned many things afterwards. when I was in my first year I didn’t know how to strengthen my problem-solving skills so I went to my seniors and ask a solution for it and then they gave a solution if you want to test your problem-solving skills you should participate in weekly coding contests. but firstly you should have learned some basic patterns of DSA . it will enhance your problem-solving skills and your speed will gradually increase do not overthink if you are not able to solve the problem you can see the solution after the contest and learn how the problem will solved. I took this advice seriously.

My first coding contest

when I was in my first year I knew that Geeksforgeeks conducted a weekly coding contest and it also provided amazing goodies who scored a good rank in the contest so I registered for the contest there were 4 questions in the contest and I solved the first question easily because it is related to a prime number which I recently learned but the second question seems tough to me I find the right approach but not able to implement it during the contest. After all, it is related to an array and at that time did not know the concept of prefix sum . but was not demotivated by this because it was the first time I had given such kind of contest and remembered what my senior said to me after the contest ended I saw the solution and learned the concept of prefix sum and the next time I gave the contest this approach helped a lot of times.

Tips I want to give from my learnings

  • Participate in weekly contests will give you different benefits
  • Your timing and problem-solving speed will be increased by giving weekly contest
  • And never demotivated when a new question comes and you are not able to solve it just see the solution after the contest ends and learn how the question solved
  • Whenever you learn a new concept like binary search, sliding window or two pointers solve different questions using these concepts and you never forget these concepts
  • Remember you can not become a proficient problem solver in a day it takes time so trust the process and believe in consistency.

Please Login to comment...

Similar reads.

  • Write It Up 2024
  • Experiences

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Please ensure that your password is at least 8 characters and contains each of the following:

  • a special character: @$#!%*?&

IMAGES

  1. problem solving questions in javascript

    problem solving questions for javascript

  2. problem solving questions for javascript

    problem solving questions for javascript

  3. problem solving questions for javascript

    problem solving questions for javascript

  4. JavaScript Problem Solving & Algorithms Guide

    problem solving questions for javascript

  5. JavaScript Problem Solving, Problem: 02. Variable.js Problem

    problem solving questions for javascript

  6. Problem Solving with JavaScript

    problem solving questions for javascript

VIDEO

  1. Problem solving question #4 of #javascript #shorts

  2. #116 Javascript Interview Questions

  3. JavaScript and Problem Solving Course: Sample Lesson

  4. javascript basic problem solving session

  5. [LIVE] JavaScript Question Solving

  6. 30 JavaScript Quiz Questions Explained

COMMENTS

  1. 2,500+ JavaScript Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. 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 ...

  2. Free Javascript challenges online

    JSchallenger recognizes what skill level you're on and adjusts the difficulty of the next challenges automatically. Making you continuously improve your Javascript skills in a short amount of time. JSchallenger. Free Javascript challenges. Learn Javascript online by solving coding exercises. Javascript for all levels.

  3. 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!

  4. JavaScript Exercises, Practice Questions and Solutions

    If you are a JavaScript learner, then Practice JavaScript Online (JavaScript Exercises) by solving JavaScript quizzes, track progress, and enhance coding skills with our engaging portal. These JavaScript practice questions are ideal for beginners and experienced developers. So, to test your skills, go through these JavaScript exercises with ...

  5. Problems

    Less than a day. W3. W4. W5. Redeem Rules. 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.

  6. 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.

  7. Level up your JavaScript skills with 10 coding challenges

    For this problem, we need to: Initialize and Declare Variable for Longest String. Loop through the array. Find the length of each string. Determine if that length is the largest we have seen so far. Replace the longest/largest variable with the arr [index] as long as length is greater than the variable.

  8. Practice JavaScript

    Get hands-on experience with Practice JavaScript programming practice problem course on CodeChef. Solve a wide range of Practice JavaScript coding challenges and boost your confidence in programming. ... The problems are based on basic logic, and definitely, the learner who is a beginner will enjoy solving such problems and will improve day by ...

  9. 37 Essential JavaScript Interview Questions

    (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 ...

  10. 10 JavaScript Code Challenges for Beginners

    6. Sort an array from lowest to highest. You could create a function for this solution as well, but be sure to try your program with varying lengths and types of arrays. Try one with all integers, another with negative numbers, and another with decimals. 7. Create a function that filters out negative numbers.

  11. JavaScript Exercises

    We have gathered a variety of JavaScript exercises (with answers) for each JavaScript Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  12. Top 50 JavaScript Interview Questions With Example Answers

    JavaScript equality operator code comparing x and y variables. | Image: Akshay Kumar. 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.

  13. Free JavaScript Challenges online ‒ JSCodebox

    Solve free JavaScript challenges online. Earn experience and share your solutions with other programmers. Free and without required login!

  14. 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 ...

  15. Solve common problems in your JavaScript code

    Basic math in JavaScript — numbers and operators; Handling text — strings in JavaScript; Useful string methods; ... Common questions. Common questions; Use HTML to solve common problems; ... View this page on GitHub • Report a problem with this content. Your blueprint for a better internet.

  16. JavaScript Online

    JavaScript Online: practice JavaScript for fun or technical interviews. Solve problems and test them online immediately! Toggle navigation JavaScript Online. ... Press "Start Coding!" below to find a random problem you haven't already solved, or pick your favourite from the "List of Problems". Start Coding!

  17. JavaScript Coding Challenges for Beginners

    Practice JavaScript by working on these coding challenges. YouTube Channel. After you read this article, please remember to check out also the "Coding Adventures" YouTube channel.

  18. 10 Common JavaScript Interview Questions (and Answers)

    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 ...

  19. List of Problems

    JavaScript Online: practice JavaScript for fun or technical interviews. This page contains the list of all available problems to solve. ... If you have solved a problem, its row turns green. Click on any problem to start coding! ID Name Difficulty; 1: Fizz Buzz: 2: Prime Numbers: 3: Number to Text: 4: Pyramid and Eggs: 5: Merge: 6:

  20. JavaScript Exercises, Practice, Solution

    JavaScript is a cross-platform, object-oriented scripting language. It is a small and lightweight language. Inside a host environment ( a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them. JavaScript contains a standard library of objects, such as Array, Date, and Math, and a ...

  21. Solve Tutorials

    Improve your Javascript basics. Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  22. 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.

  23. 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 ...

  24. javascript

    I know in javascript we have toFixed function using which I can control the decimal points but I don't want to resolve this problem using any external or Javascript function. I guess it is not possible using Pure Math but just want to know if it is possible to get back the exact value with exact decimal point (without using any external or in ...

  25. My Journey of Learning Problem-Solving Skills through ...

    My Journey of Learning Problem-Solving Skills through Coding Contests. I still remember the day I gave my first coding contest because I learned many things afterwards. when I was in my first year I didn't know how to strengthen my problem-solving skills so I went to my seniors and ask a solution for it and then they gave a solution if you ...

  26. Mathway

    Free math problem solver answers your algebra homework questions with step-by-step explanations. Mathway. Visit Mathway on the web. ... Download free on Amazon. Download free in Windows Store. get Go. Algebra. Basic Math. Pre-Algebra. Algebra. Trigonometry. Precalculus. Calculus. Statistics. Finite Math. Linear Algebra. Chemistry. Physics.