Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function name required here?

I've been testing this in the browser console of FireFox, not sure if other javascript environments have this:

◄ {x:function(){console.log("test");}}["x"]();
► SyntaxError: function statement requires a name

Why? This works though:

◄ ({x:function(){console.log("test");}})["x"]();
► undefined
► "test"

(In case anyone is wondering: I really hate the switch,case,break syntax. I'd rather use this construction.)

like image 859
Stijn Sanders Avatar asked Apr 16 '26 00:04

Stijn Sanders


1 Answers

The brackets in the first one is resulting in a block statement.

The first one looks like this when the semicolons are injected

{
    x : function() { 
        console.log("test");
    }
};
["x"]();
like image 135
epascarello Avatar answered Apr 18 '26 13:04

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!