3
votes

Might ask this on a different channel. I have this:

const reduceList = (list) => {

  return list.filter(Boolean).reduce((a, b, c) => {
    console.log({this});
  });


};

console.log(reduceList([1, 2, 3]));

I get:

console.log({this});
                 ^

SyntaxError: Unexpected token } at new Script (vm.js:74:7) at createScript (vm.js:246:10) at Object.runInThisContext (vm.js:298:10) at Module._compile (internal/modules/cjs/loader.js:657:28) at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10) at Module.load (internal/modules/cjs/loader.js:599:32) at tryModuleLoad (internal/modules/cjs/loader.js:538:12) at Function.Module._load (internal/modules/cjs/loader.js:530:3) at Function.Module.runMain (internal/modules/cjs/loader.js:742:12) at startup (internal/bootstrap/node.js:266:19)

anybody know why that is? I am on Node.js version 11.

1
That's actually really interesting since reserved words can be object property names.Andrew Li

1 Answers

2
votes

Shorthand object initializer syntax requires an Identifier. While this (and other reserved words) is technically an IdentifierName it cannot be used as an Identifier as explained in the ECMAScript spec.

A reserved word is an IdentifierName that cannot be used as an Identifier.

https://www.ecma-international.org/ecma-262/6.0/#sec-reserved-words

So this isn't limited to the this keyword, a similar syntax error can be produced with other reserved words:

{true} // syntax error
{true: true} // valid object literal

Essentially you need to use a named identifier (a variable) for things to work correctly here. It's possible to use a reserved word as a property's name, but not as an Identifier because they are evaluated differently.