You-dont-know-js: Concise (shorthand) method is named or anonymous?

Created on 10 Oct 2017  Â·  2Comments  Â·  Source: getify/You-Dont-Know-JS

In this part, it is mentioned that concise method is anonymous, but I found the definition on MDN:

The shorthand syntax uses named function instead of anonymous functions (as in …foo: function() {}…).

But I tried the given code example in Chrome devtool and did get ReferenceError:

function runSomething(o) {
    var x = Math.random(),
        y = Math.random();

    return o.something( x, y );
}

runSomething( {
    something(x,y) {
        if (x > y) {
            return something( y, x );
        }

        return y - x;
    }
} );

I also tried shorthand method in Babel, and it's transpiled into named method:

const o = {
  foo() {console.log('foo')}
}

transpiled into

var o = {
    foo: function foo() {
        console.log('foo');
    }
};

If the shorthand method is named (like MDN said), I should not get an error...it's really confusing to me now. Could you explain this for me? Thank you!

Most helpful comment

Concise methods are indeed lexically anonymous. The spec is quite clear on this topic.

MDN is wrong. Babel (in your simple case) is misleading. Try this code in Babel and see:

var o = {
   foo(x) {
      if (x > 3) return foo(x / 2);
      return x;
   }
};

o.foo(10);

You'll see that in both the console and in Babel, you'll get a ReferenceError, because foo(..) is not an available lexical name inside itself.

All 2 comments

Concise methods are indeed lexically anonymous. The spec is quite clear on this topic.

MDN is wrong. Babel (in your simple case) is misleading. Try this code in Babel and see:

var o = {
   foo(x) {
      if (x > 3) return foo(x / 2);
      return x;
   }
};

o.foo(10);

You'll see that in both the console and in Babel, you'll get a ReferenceError, because foo(..) is not an available lexical name inside itself.

Thank you for helping me!

Was this page helpful?
0 / 5 - 0 ratings