Reversing words in a string in JavaScript

We are required to write a JavaScript function that takes in a string. The function should return a new string that has all the words of the original string reversed.

For example, If the string is −

const str = 'this is a sample string';

Then the output should be −

const output = 'siht si a elpmas gnirts';


The code for this will be −

const str = 'this is a sample string';
const reverseWords = str => {
   let reversed = '';
   reversed = str.split(" ")
   .map(word => {
      return word
   .join(" ");
   return reversed;


The output in the console −

siht si a elpmas gnirts