The short short version: it looks a function call but is being interpreted as a function definition. why?
Note: x is not defined prior to execution. Also these code samples run in the node terminal. For them to run in the browser you need to preface it with someVar=
or wrap it in parens … not sure why … but this is not my main question.
I have this piece of code
{x(arg){console.log('Hello '+arg)}}.x('world')
Which seems to be equivalent to this piece of code
{x:(arg)=>{console.log('Hello '+arg)}}.x('world')
What is the reason or use case or history of why this behaves this way? I can’t for the life of me see why in the 1st example when the function execution syntax is supplied it doesn’t attempt to call the function, see it’s undefined, and throw an error. Furthermore javascript instead creates an object with a key of the undefined functions name, with the arguments matching the parameters passed, and body as the block that follows this function call. What special context is this?
I tried to run this and expected an error but I got unexpected behavior. I am aware that an object literal that contains a comma separated list of variables will create an object whose keys are the same names as those variables, but this behavior seems to be more than that.
2
Answers
It is an "object literal method definition", that’s why it works.
See this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#method_definitions
There are a couple of things going on here:
someVar
) being defined via an object literal.arg
.It’s a little easier to read if you add line breaks:
The same function can also be written this way, and it’s a little clearer:
Or yet another, even simpler way that de-couples object definition from function execution: