java script reverse code example

Example 1: javascript string reverse

"this is a test string".split("").reverse().join("");
//"gnirts tset a si siht"

// Or
const reverse = str => [...str].reverse().join('');

// Or
const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, '');

// Or
const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`;

// Example
reverse('hello world');     // 'dlrow olleh'

Example 2: js reverse

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
//["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
//["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
//["three", "two", "one"]

Example 3: reverse array in javascript

const reverseArray = arr => arr.reduce((acc, val) =>  [val, ...acc], [])

Example 4: reverse an array javascript

const reversed = array1.reverseconst reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

Tags:

Java Example