skip to Main Content

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


  1. 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

    // Shorthand method names
    const object = {
      property(parameters) {},
    }
    
    Login or Signup to reply.
  2. There are a couple of things going on here:

    1. There is an object (someVar) being defined via an object literal.
    2. Within the object, there is one property (named ‘x’), which is a function (also called a method). That method takes one parameter of arg.
    3. Directly after the object literal is closed, the dot notation is being used to call an object property (the ‘x’ method) and pass the parameter.

    It’s a little easier to read if you add line breaks:

    const someVar = {
        x(arg){
            console.log('Hello '+arg)
        }
    }.x('world')
    

    The same function can also be written this way, and it’s a little clearer:

    const someVar = {
        x: function(arg) {
            console.log( `Hello ${arg}` )
        }
    }.x('world')
    

    Or yet another, even simpler way that de-couples object definition from function execution:

    // define the object
    const someVar = {
        x: function(arg) {
            console.log( `Hello ${arg}` )
        }
    }
    
    // call the method
    someVar.x('Hello')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search