How to write multiple lines of code in Node REPL

后端 未结 5 2161
一个人的身影
一个人的身影 2020-12-23 19:35

I would like to evaluate

var foo = \"foo\";
console.log(foo);

as a block, instead of evaluating line by line

var foo = \"f         


        
5条回答
  •  孤城傲影
    2020-12-23 20:08

    Node.js REPL supports blocks and is able to return the last expression from a block, so do some other console implementations (Chrome devtools console).

    This may result in syntax error, this is a breaking change in Node 10.9.0. { could be a object literal, a block cannot be unambiguously evaluated as a block:

    {
    var foo = "foo";
    console.log(foo);
    }
    

    While this can be unambiguously evaluated as a block and will return undefined:

    ;{
    var foo = "foo";
    console.log(foo);
    }
    

    Since the last expression from a block is logged, console.log isn't needed here:

    ;{
    var foo = "foo";
    foo;
    }
    

    Notice that this is block scope, so let, const and class won't leak to REPL scope, this behaviour can be desirable or not.

提交回复
热议问题