9

When I call function hi()() with double brackets the function displays hi output and it will also give error saying, that hi is not function.

<html>
    <head></head>
<script>

function hello()
{
    document.write("hello");
}
function hi()
{
    document.write("hi");
    return "hello";
}
hi()();
</script>
</html>

What is the meaning of using ()() with function name?

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
  • 1
    Please edit the title to specify your question is about double parenthesis, not double brackets. – volpato Apr 13 '21 at 13:29

5 Answers5

13

The double parenthesis would have been useful if hi had returned a function instead of its name, like in

function hi(){
    return hello;
}
hi()();

That's probably what was the intent.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
11

Putting () after something that evaluates to a function will call that function. So, hi() calls the function hi. Assuming hi returns a function then hi()() will call that function. Example:

function hi(){
    return function(){return "hello there";};
}

var returnedFunc = hi();  // so returnedFunc equals function(){return "hello there";};
var msg = hi()();         // so msg now has a value of "hello there"

If hi() doesn't return a function, then hi()() will produce an error, similar to having typed something like "not a function"(); or 1232();.

Ben Jackson
  • 11,722
  • 6
  • 32
  • 42
10

()() means calling a function and if returns another function second parenthesis will call it.Please find below example :

function add(x){
    return function(y){
        return x+y;
    }
}

add(3)(4)

output: 7

in above case add(4) will be called for add function and add(3) will be called for returned function. here value of parameter x is 3 and parameter y is 4.

Please note : we use parenthesis for function call.

RVCoder
  • 522
  • 4
  • 14
4

The return value of this function is a string which is not a callable object.

function hi()
{
    document.write("hi");
    return "hello"; // <-- returned value
}

But if you want to call this function multiple times you can use a for-loop or some things else.

Example of hi()():

function hi(){
    return function(){ // this anonymous function is a closure for hi function
       alert('some things')
    }
}

JS Fiddle: here

If you want to call hello function immediately after hi try this:

 function hi()
    {
        document.write("hi");
        return hello; //<-- no quote needed
        // In this context hello is function object not a string
    }
frogatto
  • 28,539
  • 11
  • 83
  • 129
0

You can use eval() to execute it even if it's string : eval(hi()+'()');

Charaf JRA
  • 8,249
  • 1
  • 34
  • 44