简体   繁体   中英

Why doesn't this snippet work in the node repl?

I just started playing with ES6 and Node, experimenting with the new features in a node repl:

{
  const str = 'Alice';
  let arr = [];

  for (let c of str) {
    arr.push(c);
  }

  arr;
}

Errors thrown:

const str = 'Alice';
      ^^^
SyntaxError: Unexpected identifier

  arr;
ReferenceError: arr is not defined

I couldn't figure out what I did wrong (thinking maybe the block statement doesn't work that way), so I turned to the Chrome console to confirm. The snippet works fine. So why it doesn't work in the node repl (v7.8.0)?

Eh, the problem is how you have defined your code in {...} . It should work as expected, as you have said that it works in chrome's dev console. ( note, what you did is somewhat unusual use of the destructuring assignment but ... it's a nice thing to know why it doesn't work in repl! )

Apparently repl stops creating when you're using the ending curly brace, the } , thus executing the content defined within { and } . Let add your code step by step in repl and you will get an error when you add the } of your for-loop:

> {
... const str = 'Alice';
... let arr = [];
... for (let c of str) {
..... arr.push(c);
..... }
const str = 'Alice';
      ^^^
SyntaxError: Unexpected identifier

So the code that the parser receives is

{
  const str = 'Alice';
  let arr = [];

  for (let c of str) {
    arr.push(c);
  }

Which is of course not correct. If you re-write the code a bit, without having an ending } in the scope, then it works! Try this code

{
  const str = 'Alice';
  let arr = [];
  for (let c of str) arr.push(c);
  arr;
}

image:

在此输入图像描述

This works. The problem may lie at how node repl treats the {} stuff.

UPDATE

I was intrigued, so checked this further. The problem is that repl starts to evaluate your statement once you have pressed after placing a } character. I have checked this and if you do the following:

{
    const a = 'Alice';
    let arr = [];
    for (let c of a) {
        arr.push(c);
    } arr; }

Please note the use of two } in one line. You will get an answer;

> {
...     const a = 'Alice';
...     let arr = [];
...     for (let c of a) {
.....         arr.push(c);
.....     } arr; }
[ 'A', 'l', 'i', 'c', 'e' ]

Congratulations. You have discovered a bug in node repl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM