Basic Algorithm Scripting. Reverse a String

Hi everyone,

There is a lesson freecodecamp

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…

Hi,

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("").

2 Likes

function reverseString(str) {

let temparr=;

let revStr="";

for(let i=0; i<str.length; i++){

temparr[i] = str[str.length-(i+1)];

revStr += temparr[i];

}

return revStr;

}

console.log(reverseString(“hello”));

1 Like

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;
}

Hope this can help

Hi @mohammedelgammal!

Thank you for your response.

This topic was already marked with a solution and hasn’t been active for over 7 months.

Please try to respond to newer topics.

Thanks!