Computer >> Computer tutorials >  >> Programming >> Javascript

How to reverse a string using only one variable in JavaScript


We are required to write a JavaScript program that given any string uses only one extra variable and produces a reversed string −

  • The program should not declare or use any inbuilt or custom function.

  • The program should only make use of vanilla JS and basic loops if required.

Example

The code for this will be −

const string = 'abcdef';
let reverse = '';
while (reverse.length !== string.length) {
   const index = string.length − 1 − reverse.length;
   reverse += string[index];
};
console.log(reverse);

Output

And the output in the console will be −

fedcba