5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js REPLでは^{.*}$は()で括られる

Last updated at Posted at 2015-12-16

ECMAScriptの有名な話として{} + {}NaNであるというものがありますが、Node.js REPLで実行すると

> {} + {}
'[object Object][object Object]'

となります。
これはREPLの実装中{で始まり}で終わる行は()で括ってしまうという動作があるためです。

lib/repl.js
      var evalCmd = self.bufferedCommand + cmd;
      if (/^\s*\{/.test(evalCmd) && /\}\s*$/.test(evalCmd)) {
        // It's confusing for `{ a : 1 }` to be interpreted as a block
        // statement rather than an object literal.  So, we first try
        // to wrap it in parentheses, so that it will be interpreted as
        // an expression.
        evalCmd = '(' + evalCmd + ')\n';
      } else {
        // otherwise we just append a \n so that it will be either
        // terminated, or continued onto the next expression if it's an
        // unexpected end of input.
        evalCmd = evalCmd + '\n';
      }

この動作は行末に // などを入れておけば避けることができます。

> {} + {} //
NaN

行頭と行末を見ているだけなので次のようなコードも当然動きます。

> {a : 1}).a + ({}
'1[object Object]'

ES.nextの仕様をbabelなどのtranspilerのみで確認するのは危ないという話がありますが、同様に言語の仕様をREPLのみで確認するのもなかなか危険だなと思いました。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?