JavaScript Interview Exercises With Solutions 2019

J

I find it extremely beneficial to ask a job seeker to solve some of the following exercises. It helps to understand how good is a person you’re dealing with in JavaScript and also shows how he or she thinks about the problems in general.

In this article, I’d like to share some of those exercises.

Just putting them here in no particular order. Feel free to use any of them in your next interview.

What is reduce? Please implement map and filter functions with reduce.

SOLUTION: Reduce is functions on an array, which allows to iterate through the array and collect a result to return (which can be modified on each iteration). It takes a reducer function and an initial value for the accumulator.

  • Here’s how we can implement map:
  • And here’s filter:

Write the uniq function that removes repeated elements from the array.

SOLUTION:

An even shorter solution is possible if we utilize Set which can’t have non-unique members:


Flatten is a function that puts elements from the inner arrays into the top array. Can you implement deepFlatten so that

deepFlatten([1, [2], [[3], [4, [5]]]]) // => [1, 2, 3, 4, 5]


How many users per hobby?

Assuming we have an array of users

For each hobby, count the number of users having it.

SOLUTION:

SOLUTION 2 (Imperative):


Write a sample(arr, n) function that takes n random elements from an array.

SOLUTION:


Write a memoize function that wraps a given function and only runs it once for a list of parameters, saves the result in inner cache and return it the next time.

SOLUTION (Basic):

This solution is very simple. But it doesn’t work for some cases. We can make it more complex by asking: what if a function returns a boolean, what if a function is type-unsafe ( 1 vs “1” ), …


Can you implement a function that will get a value from an object by logical path “a.b.c” no matter how deep, and will return null if no value is there without throwing an exception.

safeGet({a: { b: 5} }, 'a.b') // => 5

SOLUTION:

What if we want to support cases like ‘a[5].b.c’?


Currying is when you can call a function with only some arguments and it returns a new function which you can use with the rest of the arguments. Write a curry function.

Example:

SOLUTION:


Where To Go From Here

Recent Posts

Categories

Meta