I completed it on my own, but when I looked into solutions I’ve found interesting and neat solution:
function reverseString(str) {
return str
.split("")
.reverse()
.join("");
}
Question: why is RETURN STR at the top, and “actions” are after it… I kinda understand what each of the following lines do but I just don’t understand why the function returns str before splitting, reversing and joining it…
It doesn’t return str before it does those “actions”, it ignores white space, in this instance new line it is same as str.split("").reverse().join("").
Basic Solution: Without Using the Built-in Functions
Here we emulated the split method then reverse then at last join for those curious about how they work
function reverseString(str) {
//declaring variables
let charsArray = [],
reversedArray = [],
stri = "";
//split method
for (let char of str) {
charsArray.push(char);
}
//reverse method
for (let i = charsArray.length-1; i >= 0; i--) {
reversedArray.push(charsArray[i]);
}
//join method
reversedArray.forEach(char => stri += char);
return stri;
}