Interview Question - JavaScript String Split and map

This is an interview question on JavaScript String split and map functions.

Code

let fruits = 'Banana, Peach'
let results = fruits.split().map(fruit => {
if(fruit === 'banana') return fruit.concat(' is yellow')
if(fruit === 'peach') return fruit.concat(' is green')
return fruit.concat(' are good for health')
})
console.log(results)

Full Transcript

In this question, we start with a string called fruits. Next we are using split method on strings followed by the map method on the resulting array and performing the conditional checks, using if loop, and finally returning an answer and logging it on the console. Let's work together to find the right answer.

In the first line, we initialize a string using a let keyword. The string is separated by comma (,) here. In the next line, there are multiple things going on at the same time. First, we are using split method on string fruits. If you look at the documentation of split method, you will find that the separator is optional. And if the separator is omitted, the result of the split is an array with one element containing the actual string. So the result of fruits.split() will be an array with one element containing the actual string. Running a map method on array with single assignment will run only one time. The fruit variable inside map method will refer to the original string banana, peach separated by comma. Then inside function body, the first two checks will result in false falling to the last line where the original string will concatenate with string "are good for health". So the correct answer is "banana peach are good for health" inside and array as a single element. Let's run the code in IDE to prove that. As I go ahead and run the code, we can confirm that the final result is "banana peach are good for health" as a single element in the array.