How to use Stack In Javascript
In this approach we use stack data structure. We iterate through each character of the input string and push it onto the stack. Then, we pop each character from the stack one by one and concatenate them to form the reversed string.
Example: This code uses the stack to reverse a string in JavaScript.
function reverseString(str) {
const stack = [];
// Push each character onto the stack
for (let char of str) {
stack.push(char);
}
// Pop each character from the stack to reverse the string
let reversed = '';
while (stack.length > 0) {
reversed += stack.pop();
}
return reversed;
}
console.log(reverseString('w3wiki'));
Output
skeeGroFskeeG
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"