How to use Spread Operator In Javascript
The spread operator(…) is used to spread the characters of the string str into individual elements. The reverse() method is then applied to reverse the order of the elements, and join() is used to combine the reversed elements back into a string.
Example: The below code uses the spread operator to split the string into a series of characters and reverse it.
// Function to reverse string
function reverseString(str) {
const strRev = [...str].reverse().join("");
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"