Question: Write a method that reverses a string. Your method will receive one argument, a string, and be expected to output that string with its letters in reverse order.
initially assign an empty string; let newString = "";
using a for loop iterate through each letter
start at the last letter and print out each letter into the empty string
input str = "hello" input str index = "h - 0, e - 1, l - 2, l - 3, o - 4" input str length = 5 let newString = "";for loop:var i = str.length-1; // str.length - 1 = 4; this means you are starting at the 4th index and the last letter, in this case "o"i >= 0; // will run the condition as long as i is greater than or equal to 0, our initial i is 4, which is greater than and equal to 0i --;// decrement by one 1. i = 4, i >= 0, (is 4 greater than or equal to 0 - yes), i -- 2. i = 3, i >= 0, (is 3 greater than or equal to 0 - yes), i -- 3. i = 2, i >= 0, (is 2 greater than or equal to 0 - yes), i -- 4. i = 1, i >= 0, (is 1 greater than or equal to 0 - yes), i -- 5. i = 0, i >= 0, (is 0 equal to 0 - yes), i --inside for loop:newString = newString + str[i]1. "" = "" + o 2. o = o + l 3. ol = ol + l 4. oll = oll + e 5. olle = ollo + h 6. ollehreturn newString ----> "olleh"
4. Code
function reverseString(str){ let newString = ""; for (var i = str.length-1; i >= 0; i --){ newString = newString + str[i] } return newString}
5. Revise
once you are done the problem see if you can go back and refactor the code to be more efficient
in this example, we can shorten the condition inside the for loop to fewer words
function reverseString(str){ let newString = ""; for (var i = str.length-1; i >= 0; i --){ newString += str[i]} return newString}