0

I'm trying to be all cool and modern and use arrow function es6 js but failed at the first attempt.

Why does this arrow function sumRange NOT work:

    var output = sumRange(3);
    console.log(output);    

sumRange = (num) => {
            if(num == 1) return 1;
            console.log(num);
            return  num + sumRange(num - 1);
        }

But here the function DOES work:

   var output = sumRange(3);
console.log(output);

function sumRange(num){
    if(num == 1) return 1;
    console.log(num)
    return num + sumRange(num - 1);
}
artworkjpm
  • 1,255
  • 2
  • 19
  • 40
  • 3
    `function` declaration statements are treated as if they appeared at the very top of the enclosing scope. If you move the first two lines to *after* the point at which you initialize `sumRange`, your first bit of code would work. – Pointy Apr 10 '19 at 12:36
  • `sumRange = function (num) { ... }` won't work either – hackape Apr 10 '19 at 12:37
  • See the linked question's answers, they apply just as much to arrow function expressions as to traditional function expressions. – T.J. Crowder Apr 10 '19 at 12:40
  • 1
    The first thing to do in this situation is to look at the error in the error in the web console, which would give you a hint about what the problem is. (In your case: `Ucaught ReferenceError: someRange is not defined`). – T.J. Crowder Apr 10 '19 at 12:42

1 Answers1

1

Bring the console.log() after the declartion of arrow function.

Note: that you are not declaring function with any keyword. You should use let var or const to declare the function.

let sumRange = (num) => {
    if(num == 1) return 1;
    console.log(num);
    return  num + sumRange(num - 1);
}

var output = sumRange(3);
console.log(output);           
        

Why does second one works?

Because that is function statement. And it can be used even before it declaration.

Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. You can use the function before you declared it

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • *"In global scope its fine..."* No, it isn't, implicit globals are never fine. :-) – T.J. Crowder Apr 10 '19 at 12:41
  • @T.J.Crowder I didn't know about that can you please explain a little. – Maheer Ali Apr 10 '19 at 12:42
  • See [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) on my anemic little blog. Even if at global scope, declare your variables. (Best: Don't create global variables at all.) – T.J. Crowder Apr 10 '19 at 12:43