3

I'm trying to write a simple code in node's REPL but am coming across some difficulties:

When typing commands one line at a time everything is working fine,
but when wrapping it with the parenthesis block { ... code ... }
(and hitting enter after each line) I'm getting an error after the closing one (}).

enter image description here

As you can see in the image I've added - executing the same code, one line at a time, is working fine.

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
GrizzlyMcBear
  • 304
  • 1
  • 15
  • Hint: `{}` is an object literal – nem035 Jan 19 '16 at 08:36
  • node v5 wont even close the block so your older version is closer! why would you want to do this anyway? I suspect there is a good reason why a REPL will not execute arbitrary blocks of codes like that – Matt Styles Jan 19 '16 at 08:38
  • Thanks @nem, but I want to write a code block (testing js not in a single line via the REPL). – GrizzlyMcBear Jan 19 '16 at 08:47
  • @MattStyles - don't know node v5 (but would look into it if time permits), the reason is written above, and luckily - we can do it :) – GrizzlyMcBear Jan 19 '16 at 08:48
  • The extra/closing semi-colon also works in node v5! Multi-line away! I normally just execute a small file, but I can see how multiline is useful. – Matt Styles Jan 19 '16 at 08:52

2 Answers2

2

Your interpreter thinks you're going to make an object literal, like { var: x } would be. { var x; } is not a good object syntax, as there should be a colon after the indentifier var, not x. Thus, SyntaxError.

You can force the parser to think it's a code block after all by prepending any of the hints that it is actually a code block:

label: { var x; }

if (true) { var x; }

do { var x; } while (false);

EDIT: Also, note that there is no good reason to do this. If you are not using a code block as a statement group for a flow control statement, or as a target for a label, it is utterly useless (and a potential source of hard-to-track bugs, as you found).

In other languages, you might be controlling the scope of variables (I expect you wanted to make sure x was not visible outside the block?). In JavaScript, only functions have scope. Thus, to isolate variables from the surrounding environment, you need a function:

{
  var x1;
};
x1; // undefined

(function() {
  var x2;
})();
x2; // Uncaught ReferenceError: x is not defined
Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Got it,
I should have added a ; after the parenthesis.

This is the result of running the code now:

enter image description here

GrizzlyMcBear
  • 304
  • 1
  • 15