JessLovely
JessLovely

Reputation: 142

Why is this spread operator causing a SyntaxError: Unexpected token in Node 7.8.0?

Here's the code snippet first, I'll deconstruct it in a moment.

this.argArr = [['arg1', 'arg2'], ['foo', 'bar'], ['you get ', 'the point']];

this.evalArgsFromArr = function () {
  var out = [];
  for (var _ = 0; _ < parent.argArr.length; _++) {
    out.push(someFunction(...parent.argArr[_])); // This part crashes
  }
  return out;
};

This function is part of an object, of course.

The idea is that, each item in parent.argArr should be an array, containing two arguments for someFunction(), which also handily serve as a human-readable condensation of the output. My understanding is, used on an iterable object (such as the arrays stored in parent.argArr), the spread operator outputs each individual value separately. (For example, the first run of the for loop should output someFunction('arg1', 'arg2').)

Whenever I run a file containing this in Node.js or PHP I get a SyntaxError: Unexpected token, citing the spread operator [...].

Here's the error message, if it helps: Error Message

I'm using Node 7.8.0.

Upvotes: 0

Views: 1041

Answers (2)

rsp
rsp

Reputation: 111434

I think this is a punishment for using underscore as a variable name. But seriously, looking at your code it seems that it should work, but only if your Node interpreter is new enough to support it.

To see the support of spread operator in Node versions, see:

To use modern syntax on platforms that don't support it natively, use Babel:

Of course we cannot really test it because you didn't provide a runnable example.

But you can see this answer:

and see if you can run the example there. It uses the spread operator and if it is tested to work correctly. If it runs on your system then you should be able to use the spread operator. If it doesn't then you should really upgrade Node because there's no reason of using such an outdated version.

If all else fails then you should always be able to change:

someFunction(...array);

to:

someFunction.apply(undefined, array);

See the docs:

By the way, I'm not sure what you mean by saying that one line "likes to crash" - doesn't it always crash? It would be very strange.

Upvotes: 4

You must delete "...", try:

this.argArr = [['arg1', 'arg2'], ['foo', 'bar'], ['you get ', 'the point']];

this.evalArgsFromArr = function () {
  var out = [];
  for (var _ = 0; _ < parent.argArr.length; _++) {
    out.push(someFunction(parent.argArr[_]));
  }
  return out;
};

Upvotes: -1

Related Questions