3

Lets assume we have

function () {}.bind(null);

and

(function () {}).bind(null);

Why the first one doesn't work in developer console (it throws syntax error) but both of them work in code (".js" file in website).

  • 1
    I think its because you are trying to define an anonymous function. Console has no future way of referencing it so its a pointless endeavour, youre defining a function you have no way of calling. If you define it as a variable it works - `var a = function () {}.bind(null);` – Craicerjack Jun 22 '16 at 08:26
  • 1
    Also I dont think its binding related. Defining an anonymous function without binding and you have the same error. – Craicerjack Jun 22 '16 at 08:34
  • 2
    @Craicerjack i think you can write it as an answer. But why its throwing SyntaxError? – Ararat Harutyunyan Jun 22 '16 at 08:38
  • 1
    Because normally anonymous functions have to be used like variables. If you write anonymous functions you must assign them to a variable or pass them as parameter, unless you instantly call them (in that case they are called IIFE, immediately-invoked function expression). The error you receive is that the parser see it as a function declaration where you forgot to put the function name – valepu Jun 22 '16 at 08:40
  • here an explaination why adding parens works: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – valepu Jun 22 '16 at 08:43

1 Answers1

3

I think its because you are trying to define an anonymous function. Console has no future way of referencing it so its a pointless endeavour, youre defining a function you have no way of calling. If you define it as a variable it works:

 var a = function () {}.bind(null); 

Also I dont think its binding related. Defining an anonymous function without binding and you have the same error

Edits

A statement that begins with the keyword "function" must be a valid function declaration statement. That requires a name for the function.

In an expression (or expression statement), that rule is different; no name is necessary because the function acts as a value in that context. No name is required then.

A function declaration cannot be anonymous, but a function expression can. A stand alone anonymous function looks like a function declaration that is missing an identifier to JavaScript. But, combined with an operator, JavaScript treats an anonymous function as the operator's operand expression.

Community
  • 1
  • 1
Craicerjack
  • 5,524
  • 2
  • 27
  • 36
  • If you quote some other post, please link the exact post (the answer, not the question in this case), name the author, and mark up the citation with blockquote syntax – Bergi Jun 22 '16 at 08:47