1

I have been trying to use recursion to find the sum of a number using an anonymous function in javascript but I am getting the following error:

Uncaught SyntaxError: Unexpected token +

I want to use an anonymous function for this. Can anyone help me in finding what I am doing wrong here?

<script type="text/javascript">
    console.log(function (n) {
        if (n == 0) {
            return 1;
        }
        else {
            return function(n+function(n-1));
        }
    }(8));
</script>

3 Answers 3

5

There are several problems with what you're doing.

For starters, attempting to call the function recursively (function(n+function(n-1))) will result in a call stack size exceeded error because you're adding the sum to each argument passed to the recursive call. You probably want something closer to (n + function(n-1)).

However, this is still problematic, because you can't call an anonymous function recursively (except by using arguments.callee, which is disallowed in strict mode).

To do what it appears you're trying to do without giving a name to your function expression, you could do something like:

console.log(function(n) {
    if (n == 0) {
        return 1;
    }
    else {
        return n + arguments.callee(n-1);
    }
}(8))

However, you could also provide a name for your function expression to refer to in recursive calls, which will work in strict mode as well:

console.log(function foo(n) {
    if (n == 0) {
        return 1;
    }
    else {
        return n + foo(n-1);
    }
}(8))

edited: In the base case (n == 0) you probably want to return 0 instead of 1 if your goal is to get the sum of all whole numbers from 0 to n.

Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to accomplish this without using 'argument.callee' like passing a function as a parameter to itself?
Yes, see the second example where I provide the name 'foo' for the function expression. See kangax.github.io/nfe for more details on how this (a named function expression) differs from a function declaration.
An anonymous function in javascript just refers to an unnamed function expression.
That means we can't use unnamed function for recursion without argument.callee?
arguments.callee in the first example refers to the anonymous function. However, like I mentioned, this is disallowed in strict mode, so there is no way to get a reference to the function being invoked in that case. In your question, you attempt to use the function keyword as the identifier referring to the function being called, which is incorrect. The function keyword in javascript is used either in declaring a function, or invoking a function expression.
3
  console.log(function fn(n) {
      if (n == 0) {
          return 1;
      } else {
          return (n + fn(n - 1));
      }
  }(8));

Error in this line function(n+function(n-1)), because this is syntax error, you can not call function like you do. In our case you should add for self-Invoking function - name, and use it for recursion call stack

1 Comment

I am fairly new to javascript so I dont know whether function fn(){}; is anonymous or named. I also tried return n+function(n-1) to try to keep it anonymous. I have been given a task and I need to understand anonymous and named functions.
0

When I revised the anonymous function to use the correct recursion, namely return n + f(n-1), I discovered that oddly enough the following code works without resorting to arguments.callee as long as the script resides on an HTML page. Note: it still does not work with console.log.

One more thing, if the code in this instance is attempting to get the sum of numbers ranging from eight to one, then when n equals zero, the return value should be zero and not one for the sum to be mathematically correct.

var f = function (n) {
        if (n == 0) {
            return 0;
        }
        else {
            return n + f(n-1);
        }
};

var res = f(8); // 36

See live example at http://jsfiddle.net/d5k4ag8w/11/ Also, this article provides an easy way to figure out the math using just pencil and paper :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.