Hey, general understing about JS behavior/functioning

so here is an example from the website(see below text) of a reversed string function executed with recursion and I’m curious to understand: 1) why if I switch the return line inner actions like this:
’ return word.charAt(0) + reversed(word.substring(1))’
I get the string again not reversesd.
2) where the ‘word.charAt()’ letters are being saved, memory wise what I miss here, what keeps them accumulated with tact and where are they ‘going’
overall I’d like a good article or explanation of some kind to how the memory concept works in js(or coding overall) to understand better the relations as I code.
I hope I’m clear and I’m here to learn:)

function reverseString(str) {
  if (str === "")
    return "";
    return reverseString(str.substr(1)) + str.charAt(0);

@Ohad1 please format the code properly and include the link to the site you cite.

But the problem with that line is that the function will operate like this, if we pass “hello”:

  1. input “hello”, then charAt(0)–>h
  2. Now it executes reverse(“ello”)
  3. chatAt(0)–>e
    … this repeats
  • will return hello

When you do return reversed(word.substring(1))+word.charAt(0)
it does

  1. input “hello”, now it executes reverse(“ello”)
  2. plus charAt(0)–>h
    this is reverse(“ello”)+“h”
  3. reverse(“ello”) yields, reverse(“llo”)+“e”+“h”
    … this repeats
  • will return olleh
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

hey thanks, still try please to explain me this:
as I see it in both ways we are breaking down the letters in each nested function and the word itself towards our ‘out condition’ that from that moment will layer up the letters and create the reverserd word.
you can see it here:

Yes, they break up the letters, but they also concatenate the result. Say we do this:

  • Take word hello and split by letters to h,e,l,l,o
  • Now we concatenate o+l+l+e+h

This is different to concatenate (join the letters) in the order h+e+l+l+o

Which is what I tried to describe in the first message. Is this clear?

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.