5 typical interview questions on JavaScript: breakdown and solutions

5 typical interview questions on JavaScript: breakdown and solutions

From the Translator: we've published an article for you by Maria Perna, which discusses typical JavaScript tasks, most often offered to developer candidates during interviews. This article will be useful mainly for beginner programmers.

Interviews at tech companies have long become a common topic of discussion. It's no surprise—successfully passing an interview opens the door to a good job. However, it's not that simple, as it often requires solving complex tasks.

Moreover, most of these tasks are usually unrelated to the job the candidate will be performing, yet they still need to be solved. Sometimes this has to be done on a whiteboard without checking with Google or any other source. Yes, the situation is gradually changing, and some companies are moving away from such interview formats, but many employers still adhere to this tradition. This article is dedicated to analyzing typical JavaScript tasks that are frequently used as assignments for candidates.

Reminder: for all readers of 'Habr' - a discount of 10,000 rubles when enrolling in any Skillbox course with the promo code 'Habr'.

Skillbox recommends: Practical Course "Mobile Developer PRO".

The key is thorough preparation for your interview.

Yes, before we dive into the tasks, let's look at some general preparation tips for interviews.

The main thing is to prepare in advance. Check how well you remember algorithms and data structures and brush up on the areas you are not very familiar with. There are plenty of online platforms that can help you prepare for interviews. We recommend GeeksforGeeks, Pramp, Interviewing.io and CodeSignal.

It's important to learn how to verbalize your solution aloud. It's preferable to explain to the interviewers what you are doing rather than just writing on the board (or typing code on the computer without saying anything). This way, if you make a mistake in the code but your approach is generally correct, you can increase your chances of success.

You need to think through the task before starting to solve it. In some cases, you might superficially understand the assignment and then go down the wrong path. It might be worth asking the interviewer a few clarifying questions.

You need to practice writing code by hand, not on a computer. Sometimes, during interviews, candidates are given a marker and a board with no hints or automatic formatting. When searching for a solution, it's worth writing your code on a piece of paper or directly on the board. If you try to hold everything in your head, you might forget something important.

Template Tasks in JavaScript

Some of these tasks may already be familiar to you. You may have gone through interviews where you needed to solve something similar or practiced them while learning JavaScript. Now it's time to solve them again, this time with a detailed explanation of the process.

Palindrome

A palindrome is a word, phrase, or sequence of characters that reads the same forwards and backwards. For example, "Anna" is a palindrome, while "table" and "John" are not.

The Task

Given a string, you need to write a function that returns true if the string is a palindrome and false if it is not. Spaces and punctuation should be taken into account.

palindrome('racecar') === true
palindrome('table') === false

Analyzing the Task

The main idea here is to reverse the string. If the "reversed" string is exactly the same as the original, then we have a palindrome and the function should return true. Otherwise, it should return false.

Solution

Here is the code to solve the palindrome problem.

const palindrome = str => {
  // turn the string to lowercase
  str = str.toLowerCase()
  // reverse input string and return the result of the
  // comparison
  return str === str.split('').reverse().join('')
}

The first step is to convert the characters of the input string to lowercase. This ensures that the program compares the actual characters, not their case or anything else.

The second step is to reverse the string. This is straightforward: you need to convert it into an array using the .split() method (String library). Then we reverse the array using .reverse() (Array library). The final step is to convert the reversed array back into a string using .join() (Array library).

Now all that's left is to compare the "reversed" string with the original, returning true or false.

FizzBuzz

One of the most popular interview problems.

The Task

You need to write a function that prints numbers from 1 to n, where n is an integer passed as a parameter to the function, with the following conditions:

  • print fizz instead of numbers that are multiples of 3;
  • print buzz instead of numbers that are multiples of 5;
  • print fizzbuzz instead of numbers that are multiples of both 3 and 5.

Example

Fizzbuzz(5)

Result

// 1
// 2
// fizz
// 4
// buzz

Analyzing the Task

The main point here is the method of finding multiples using JavaScript. This can be implemented using the modulus operator or remainder — %, which allows showing the remainder when dividing two numbers. If the remainder is 0, it means that the first number is a multiple of the second.

12 % 5 // 2 -> 12 is not a multiple of 5
12 % 3 // 0 -> 12 is a multiple of 3

So when we divide 12 by 5, we get 2 with a remainder of 2. However, when we divide 12 by 3, we get 4 with a remainder of 0. In the first case, 12 is not a multiple of 5, while in the second case, 12 is a multiple of 3.

Solution

The optimal solution would be the following code:

const fizzBuzz = num => {
  for(let i = 1; i <= num; i++) {
    // check if the number is a multiple of 3 and 5
    if(i % 3 === 0 && i % 5 === 0) {
      console.log('fizzbuzz')
    } // check if the number is a multiple of 3
      else if(i % 3 === 0) {
      console.log('fizz')
    } // check if the number is a multiple of 5
      else if(i % 5 === 0) {
      console.log('buzz')
    } else {
      console.log(i)
    }
  }
}

The function executes the necessary checks using conditional operators and returns the result required by the user. The task is to pay attention to the order of if...else operators: starting with the double condition (&&) and ending with the case when no multiples could be found. As a result, we cover all scenarios.

Anagram

This refers to a word that contains all the letters of another word in the same quantity but in a different order.

The Task

You need to write a function that checks if two strings are anagrams, where the case of the letters does not matter. Only characters are considered; spaces or punctuation are not taken into account.

anagram('finder', 'Friend') -> true
anagram('hello', 'bye') -> false

Analyzing the Task

Here it is important to ensure that each letter in the two input strings is checked along with their count in each string.

finder -> f: 1 friend -> f: 1
i: 1 r: 1
n: 1 i: 1
d: 1 e: 1
e: 1 n: 1
r: 1 d: 1

To store the anagram data, it is advisable to choose a structure such as a JavaScript object literal. The key in this case is the character, while the value represents the number of its occurrences in the current string.

There are also other conditions:

  • You need to ensure that letter casing is not taken into account when comparing. Just transform both strings to lowercase or uppercase.
  • Exclude all non-character symbols from the comparison. It is best to work with regular expressions.

Solution

// helper function that builds the
// object to store the data
const buildCharObject = str => {
  const charObj = {}
  for(let char of str.replace(/[^w]/g).toLowerCase()) {
    // if the object has already a key value pair
    // equal to the value being looped over,
    // increase the value by 1, otherwise add
    // the letter being looped over as key and 1 as its value
    charObj[char] = charObj[char] + 1 || 1
  }
  return charObj
}
 
// main function
const anagram = (strA, strB) => {
  // build the object that holds strA data
  const aCharObject = buildCharObject(strA)
  // build the object that holds strB data
  const bCharObject = buildCharObject(strB)
 
  // compare number of keys in the two objects
  // (anagrams must have the same number of letters)
  if(Object.keys(aCharObject).length !== Object.keys(bCharObject).length) {
    return false
  }
  // if both objects have the same number of keys
  // we can be sure that at least both strings
  // have the same number of characters
  // now we can compare the two objects to see if both
  // have the same letters in the same amount
  for(let char in aCharObject) {
    if(aCharObject[char] !== bCharObject[char]) {
      return false
    }
  }
  // if both the above checks succeed,
  // you have an anagram: return true
  return true
}

Note the use of Object.keys() in the snippet above. This method returns an array containing the names or keys in the same order they appear in the object. In this case, the array will be as follows:

['f', 'i', 'n', 'd', 'e', 'r']

Thus, we obtain the properties of the object without the need to perform a lengthy loop. This approach can be used with the .length property to check if both strings have the same number of characters—this is an important feature of anagrams.

Finding Vowels

A fairly simple task that often comes up in interviews.

The Task

You need to write a function that takes a string as an argument and returns the number of vowels contained in that string.
The vowels are 'a', 'e', 'i', 'o', 'u'.

Example:

findVowels('hello') // -> 2
findVowels('why') // -> 0

Solution

Here’s the simplest option:

const findVowels = str => {
  let count = 0
  const vowels = ['a', 'e', 'i', 'o', 'u']
  for(let char of str.toLowerCase()) {
    if(vowels.includes(char)) {
      count++
    }
  }
  return count
}

It is important to note the use of the .includes() method. It is available for both strings and arrays. It should be used to determine if an array contains a specific value. This method returns true if the array contains the specified value and false if not.

There is also a more concise solution to the problem:

const findVowels = str => {
  const matched = str.match(/[aeiou]/gi)
  return matched ? matched.length : 0
}

Here, the .match() method is utilized, which allows for efficient searching. If the regular expression as an argument to the method is found within the specified string, the returned value becomes an array of matching characters. If no matches are found, .match() returns null.

Fibonacci

A classic problem that can be encountered in interviews of various levels. It's worth recalling that the Fibonacci sequence is a series of numbers where each subsequent number is the sum of the two preceding ones. Thus, the first ten numbers are as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

The Task

You need to write a function that returns the n-th entry in the specified sequence, where n is the number passed as an argument to the function.

fibonacci(3) // -> 2

This task requires iterating through a loop a number of times specified by the argument, returning a value at the corresponding position. This approach requires the use of loops. If you use recursion instead, it might impress the interviewer and earn you some extra points.

Solution

const fibonacci = num => {
  // store the Fibonacci sequence you're going
  // to generate inside an array and
  // initialize the array with the first two
  // numbers of the sequence
  const result = [0, 1]
 
  for(let i = 2; i <= num; i++) {
    // push the sum of the two numbers
    // preceding the position of i in the result array
    // at the end of the result array
    const prevNum1 = result[i - 1]
    const prevNum2 = result[i - 2]
    result.push(prevNum1 + prevNum2)
  }
  // return the last value in the result array
  return result[num]
}

In the results array, the first two numbers are stored in the series, as each entry in the sequence consists of the sum of the two preceding numbers. Initially, there are no two numbers to generate the next number, so the loop cannot automatically generate them. However, as we know, the first two numbers are always 0 and 1. Therefore, we can manually initialize the results array.

When it comes to recursion, things are simpler and more complex at the same time:

const fibonacci = num => {
  // if num is either 0 or 1 return num
  if(num < 2) {
    return num
  }
  // recursion here
  return fibonacci(num - 1) + fibonacci(num - 2)
}

We continue to call fibonacci(), passing smaller numbers as arguments. We stop when the passed argument equals 0 or 1.

Output

You have probably encountered one of these tasks if you've gone through interviews for frontend or JavaScript developer positions (especially at the junior level). But even if you haven't, they may come in handy in the future — at the very least for general knowledge.

Skillbox recommends:

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster