www.webdeveloper.com
Results 1 to 2 of 2

Thread: How does this work?

  1. #1
    Join Date
    Apr 2012
    Posts
    1

    How does this work?

    How does this work?

    Hello, I have a little logic problem in my head. I was trying to understand how does this code work:

    Code:
     var power = function (base, exponent){
        if (exponent === 0){
            return 1;
        }
        else {
            return base * power(base, exponent-1);
        }
    };
    
    power(2,2);
    It is from a lesson. What I am trying to find out is that: we ave defined a function with parameters base and exponent. Now it returns 0 if exponent is 1. In other cases it returns base * base^(exponent-1) which is basically x*x to the power of exponent -1.

    Now how does base*power(base,exponent-1) work because I have not defined any way in this code to calculate it. As in how does the code know that I am trying to multiply x*x*x...etc.

    I do not know if this makes any sense to any of you but if someone could explain.

  2. #2
    Join Date
    Mar 2011
    Posts
    1,139
    It's a recursive function. It repeatedly calls itself, decrementing the value of 'exponent' by 1 with each call until exponent equals 0.

    When you call power(2,2):
    First time through:
    return 2 * (power(2,1))
    Second time through:
    power(2,1)
    return 2 * (power(2,0));
    Third time through:
    power(2,0)
    return 1;
    Which is returned to the call in the second time through to resolve to:
    return 2 * (1);
    Which is returned to the call in the first time through to resolve to:
    return 2 * 2;
    Which equals 4 - and returned as the correct answer.
    Rick Trethewey
    Rainbo Design

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles