Reverse a String or Numbers in JavaScript
NotesWrite a function to reverse a string or number or reverse a string or number is most common Javascript interview questions you may expect in a JavaScript Interview. Here are a few ways to reverse the string or number.
Reverse Strings
- We can loop through the characters using decrementing
for
loop.
function reverse(input){
let output = "";
for (var i = input.length - 1; i >= 0; i--){
output += input[i];
}
return output;
}
- Another way is to use ES6’s
for...of
loop.
function reverse(input){
let output = "";
for(let char of input){
output = char + output;
}
return output;
}
- You can use JavaScript inbuilt reverse() method for arrays.
function reverse(input){
return input.split("").reverse().join("");
}
- Or you can do it the ES6 way.
function reverse(input){
return [...input].reverse().join('');
}
Reverse Numbers
Almost all above methods works for numbers as well, all you have to do is to convert the input number to string using toString()
method and reverse it, but sometimes they can ask you not to use the string conversion method. In that case you can use while loop.
function reverse(number) {
var revNumber = 0;
while (number > 0) {
revNumber = (revNumber * 10) + (number % 10);
number = Math.floor(number / 10);
}
return revNumber;
}
Hope that helps. 😄