How to use Spread Operator and reduce() method In Javascript
The spread operator can be used to convert a string into an array of characters and use reduce() function in JavaScript to make a reverse string from an array by concatenating the string in the forward direction.
Example: This code implements the spread operator and the reduce method to reverse a string.
// Function to reverse string
function reverseString(str) {
const strRev = [...str].reduce((x, y) => y.concat(x));
console.log(strRev);
}
// Function call
reverseString("w3wiki");
reverseString("JavaScript");
reverseString("TypeScript");
Output
skeeGrofskeeG tpircSavaJ tpircSepyT
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.
Examples:
Input: str = "w3wiki"
Output: "skeeGrofskeeG"
Input: str = "Hello"
Output: "olleH"