javascriptfunction-callcomma-operator

Why would a function-call expression use a comma-operator expression as the function to be called?


could someone please explain to me what is going on in the second line here ? :

var foo = function(){alert("hello?")};
(0,foo)();

Solution

  • The infamous comma expression a,b evaluates both arguments and returns the value of the right-hand expression.

    Hence in this case it's exactly the same as foo();.

    Here's a better example that will help you understand what's going on:

    function foo() {
        print("foo called");
        return 123;
    }
    function bar() {
        print("bar called");
        return 456;
    }
    var result = (foo(), bar());
    print("result:", result);
    

    Output:

    foo called
    bar called
    result: 456
    

    Also the comma expression may be confused with the comma delimiting function arguments. Not the same! Notice the difference:

    print("result:", foo(), bar() ); // 3 arguments, no comma operator
    print("result:", (foo(), bar()) ); // 2 arguments, comma operator