70 Reverse a String

Run Settings
LanguageJavaScript
Language Version
Run Command
//Create a function that reverses a string function reverse(str) { // check input for string if (!str || str.length < 2 || typeof str !== 'string') { return 'not a string'; } const backwards = []; const totalItems = str.length - 1; // how many items we have in the string for(let i = totalItems; i >= 0; i--) { // we are going to loop through the syting till i = 0. i-- : we are going from back to front, we are decrementing backwards.push(str[i]); // pushing each item of a given string into our array } const reversedString = backwards.join(''); console.log(reversedString); return(reversedString); } function reverse2(str) { const reversedString = str.split('').reverse().join(''); console.log(reversedString); return reversedString; } const reverse3 = str => str.split('').reverse().join(''); const reverse4 = str => [...str].reverse().join(''); reverse('Hello world!'); reverse2('Hello world2!'); reverse3('Hello world3!');
Editor Settings
Theme
Key bindings
Full width
Lines