Home » Javascript » recursion – How does this recursive Javascript function works (Returning the length of a string)

recursion – How does this recursive Javascript function works (Returning the length of a string)

Posted by: admin February 24, 2020 Leave a comment

Questions:

need some help.

The function returns the length of a string recursively

const length = str => str == '' ? 0 : length(str.substring(1)) + 1;

It works fine. I have difficulties to understand how the returning of the length(str.substring(1)) + 1 part works. How does everything gets added up ?. For example input: “Hello World” output: 11. Why doesn’t the function concatenate (because of ‘+’ sign) input: “Hello World” output: “Hello World11”?

Thanks

How to&Answers:

To simplify things for explanation, I’ve rewritten the function to its “long form” below:

function length(str){
  if (str == ''){
    return 0;
  }
  const substr = str.substring(1);
  return length(substr) + 1;
}

console.log(length('abc'));

So given input "abc", the steps of execution are as below:

  1. Check 'abc' == '' ==> false.
  2. Create substr = 'bc'.
  3. Invoke length('bc'):
    1. Check 'bc' == '' ==> false.
    2. Create substr = 'c'.
    3. Invoke length('c'):
      1. Check 'c' == '' ===> false.
      2. Create substr = ''.
      3. Invoke length(''):
        1. Check '' == '' ===> true
        2. Return 0.
      4. Operate 0 + 1.
      5. Returns 1.
    4. Operate 1 + 1.
    5. Return 2.
  4. Operate 2 + 1.
  5. Return 3.

As you can see, nowhere in the code would result in a concatenation of string with number.

Answer:

For example
str = “hello”
,execute the code “length(str)”
the step as follow

    length("hello")
    length("ello") + 1 
    (length("ll") + 1) + 1
    ((length("lo") + 1) + 1) + 1
    (((length("o")+1) + 1) + 1) + 1
    ((((0 + 1)+1) + 1) + 1) + 1