Goal: create a function
reverseString(str)that returns the input string reversed.
Possible solutions:
split(''), reverse(), join('')Example with array methods:
function reverseString(str) {
return str.split('').reverse().join('');
}/**
* Reverses a string by changing the order of characters
* @param {string} str - The input string to reverse
* @returns {string} The reversed string
*/
function reverseString(str) {
// 1. Split the string into an array of individual characters
// Example: "hello" -> ["h", "e", "l", "l", "o"]
// 2. Reverse the order of array elements
// ["h", "e", "l", "l", "o"] -> ["o", "l", "l", "e", "h"]
// 3. Join the reversed array back into a string
// ["o", "l", "l", "e", "h"] -> "olleh"
return str.split('').reverse().join('');
}
window.reverseString = reverseString;Why this way:
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}function reverseString(str) {
if (str === '') return '';
return reverseString(str.slice(1)) + str[0];
}Create a function reverseString that takes a string and returns a new string with the characters in reverse order.
reverseString('hello'); // 'olleh'
reverseString('a b'); // 'b a'
reverseString('madam'); // 'madam'reverseStringGoal: create a function
reverseString(str)that returns the input string reversed.
Possible solutions:
split(''), reverse(), join('')Example with array methods:
function reverseString(str) {
return str.split('').reverse().join('');
}/**
* Reverses a string by changing the order of characters
* @param {string} str - The input string to reverse
* @returns {string} The reversed string
*/
function reverseString(str) {
// 1. Split the string into an array of individual characters
// Example: "hello" -> ["h", "e", "l", "l", "o"]
// 2. Reverse the order of array elements
// ["h", "e", "l", "l", "o"] -> ["o", "l", "l", "e", "h"]
// 3. Join the reversed array back into a string
// ["o", "l", "l", "e", "h"] -> "olleh"
return str.split('').reverse().join('');
}
window.reverseString = reverseString;Why this way:
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}function reverseString(str) {
if (str === '') return '';
return reverseString(str.slice(1)) + str[0];
}Create a function reverseString that takes a string and returns a new string with the characters in reverse order.
reverseString('hello'); // 'olleh'
reverseString('a b'); // 'b a'
reverseString('madam'); // 'madam'reverseStringThe code editor is intentionally hidden on mobile.
Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.
📖 Now: Study the task, think through the solution. Act like a strategist.
💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!