0

I'm trying to incorporate some crazy callback-recursion combo into my Node.js app. After some research, I found a strange syntax to both declare and execute function in the same block. So I try this simple code to test the concept:

(function hello() {
        console.log("Hello, world!");
    })();

hello();

I expect it to just put two Hello, world!'s in the console. One immediately after declaration and one for the hello() call. However, it just prints one and then throws an error saying hello is not defined at hello().

Is there something I'm not getting here?

Jyothi Babu Araja
  • 8,434
  • 3
  • 28
  • 37
starleaf1
  • 1,997
  • 1
  • 29
  • 55
  • 10
    The point of that self-invoking function syntax is that it's *not* globally defined, so you can't invoke it afterward. – David Dec 27 '16 at 15:09
  • 2
    by wrapping it in `()` you created a new scope. Your `hello` function doesn't exist when you call it outside the `()` – deltree Dec 27 '16 at 15:10
  • @deltree The parenthesis don't create a scope. It's just that there's no assignation – Denys Séguret Dec 27 '16 at 15:11
  • @David So, I have to call `hello()` recursively for this to work? – starleaf1 Dec 27 '16 at 15:12
  • @starleaf1: Not sure what you think recursion has to do with this. You're defining a function in an enclosed expression and then executing that function. You can't call that function from outside that expression. For "this to work" I guess we'd need to know what you're trying to do here. – David Dec 27 '16 at 15:14
  • 1
    @deltree — No. The parenthesis turn the function declaration into a function expression. They change the scope the *variable* `hello` is created in (from the current scope to the scope of the new function), but they don't create a new scope. – Quentin Dec 27 '16 at 15:14
  • Possible duplicate of [JavaScript function declaration syntax: var fn = function() {} vs function fn() {}](http://stackoverflow.com/questions/336859/javascript-function-declaration-syntax-var-fn-function-vs-function-fn) – Ilja Everilä Dec 27 '16 at 15:17
  • Though this isn't an exact duplicate, the issue is pretty much covered in the function declaration vs. expression q/as, so made the connection. – Ilja Everilä Dec 27 '16 at 15:19
  • @David What I meant was, if I want to call `hello()`, I have to do it from inside the declaration. – starleaf1 Dec 27 '16 at 15:21

1 Answers1

7

A named function expression only creates a variable with the same name as itself within its own scope. This is useful if you need to call it recursively.

(function hello() {
    // "hello" exists as a variable only here, inside the function
    console.log("Hello, world!");
})();

You need a function declaration to create a matching variable in the same scope as the function is declared (and you can't immediately invoke a function declaration).

function hello() {
  console.log("Hello, world!");
}

hello();
hello();
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205