Basic JavaScript Interview Exercises
Tags: webdev, programming, beginners, javascript
Published: 2021-01-24 02:01:33

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


To get a job as a front end developer, we need to nail the coding interview.

In this article, we’ll look at some quick warmup questions that everyone should know.

### **Write a function the reverses a string**

We can use JavaScript’s string and array methods to reverse a string easily.

To do this, we can write the following function:

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

The function works by splitting the string into an array of characters, then reversing the array, and joining it back together.

We used JavaScript string’s `split` method and array’s `reverse` and `join` methods.

### **Write a function that filters out numbers from a list**.

We can do that with the `isNaN` function and the array’s `filter` method.

To solve this problem, we can write the following code:

```
const removeNums = (arr) => arr.filter(a => isNaN(+a));
```

In the `removeNums` function, we pass in an array `arr` then call `filter` on it with a callback that returns `isNaN(+a)` , which is `true` if an item is converted to `NaN` when we try to convert it to a number.

### **Write a function that finds an element inside an unsorted list.**

We can use the array’s `findIndex` method to find an element inside an unsorted list.

We write the following function:

```
const search = (arr, searchItem) => arr.findIndex(a => a === searchItem);
```

to do the search. The `findIndex` method returns the index of the first item that it finds that meets the condition in the callback.

We can use it as follows:

```
console.log(search(['foo', 'bar', 1], 'foo'));
```

to search for the string `'foo'` . We then should get 0 since `'foo'` is the first entry in the array.

### **Write a function that showcases the usage of closures.**

A closure is a function that returns a function. It’s usually used to hide some data inside the outer function to keep them from being exposed from the outside.

We can do that by writing:

```
const multiply = (first) => {
  let a = first;
  return (b) => {
    return a * b;
  };
}
```

Then we can call it by writing:

```
console.log(multiply(2)(3));
```

which gets us 6.

### **What is a Promise? Write a function that returns a Promise.**

A promise is a piece of asynchronous code that runs in an indeterminate amount of time.

It can have the pending, fulfilled or rejected states. Fulfilled means it’s successful, rejected means that it failed.

An example of a promise is the Fetch API. It returns a promise and we can use it to return a promise ourselves.

For instance, we can write:

```
const getJoke = async () => {
  const res = await fetch('http://api.icndb.com/jokes/random')
  const joke = await res.json();
  return joke;
}
```

to get a joke from the Chuck Norris API.

### **Write a function that flattens a list of items.**

We can use the array `flat` method to flatten a an array of items.

For example, we can write:

```
const flatten = arr => arr.flat(Infinity);
```

to flatten all levels of an array to one level.

We can also loop through each item of an array and recusively flatten nested arrays into one level.

For instance, we can write the following:

```
const flatten = (arr = []) => {
  let result = [];
  for (let item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result = result.concat(item);
    }
  }
  return result;
}
```

to flatten the array.

The code works by looping through each entry of the array. Then find the arrays in the entries and the `flatten` calls itself then append it to `result`. Otherwise, it just adds the item into the `result` array.

After it went through all the levels, it returns `result` .

### **Write a function that accepts two numbers** `**a**` **and** `**b**` **and returns both the division of** `**a**` **and** `**b**` **and their modulo of** `**a**` **and**`**b**`**.**

We can do that by using the `/` operator to divide `a` and `b` , and the `%` operator to find the remainder when we divide `a` by `b` .

To do that, we can write the following function:

```
const divMod = (a, b) => {
  if (b !== 0) {
    return [a / b, a % b];
  }
  return [0, 0];
}
```

We check if the divisor is zero, then we do the operations as we mentioned and return the computed items in an array.

### Conclusion

We can use arrays and string methods as much as possible to make our lives easier.

They’re also more efficient than what we implement from scratch.