A JavaScript challenge I need help in!

Begin by breaking the problem into small bits. It won’t be difficult to create the formatted return value given we have string template literal syntax at our disposal.

return `(${area}) ${prefix}-${number}`

Now just declare and define the three variables (before the return) and you’re done.

Hint: Think of slices to extract the appropriate segments of the parameter array.

const area = arr.slice(0, 3).join('')
const prefix = arr.slice(3, 6).join('')
const number = arr.slice(6).join('')

Note how each slice is joined to form the three strings.

This is by no means the only way to solve this challenge so don’t just plug in my code and call it a day. Take from it, learn and experiment with other approaches.

If you have deduced that this whole thing can be written in one line, you are correct. But that took some wherewithal that you owe it to yourself to accumulate such that the process leads to this. It has to have a starting place and candidate code that can be reduced to this final form.

Don’t carry code around in your head. Be able to construct it, criticize it, road test and evaluate it, prove it, then refine and refactor. Don’t start with the simplest possible form and expect to learn anything about how it came to be. It must have been reduced from an earlier form. Those are the forms to be learned and studied.

1 Like