1

I'm getting this error

[11:55:38] Unexpected token => at test.js :
175 |    // }
176 |  })
177 |  var f = (req, res, next) => {
------------------------------------^
178 |    return res.json('test');
179 |  };

When running this specific code.

var f = (req, res, next) => {
  return res.json('test');
};

app.get('/test', f);

I'm playing around with ES6 and I can't find a solution for this error even though my route was working properly and returning 'test'.

What is the problem with this snippet?

'use strict';

module.exports.controller = function (app) {

  app.get('/test', (req, res, next) => {
    return res.json('test');
  });
}
10
  • 1
    Which version of NodeJS? Looks like Arrow function is not supported by it. Commented May 24, 2016 at 4:03
  • 1
    Also, How your application ran (returning test), when its having error "Unexpected token => at test.js"? Commented May 24, 2016 at 4:05
  • I'm using v6.2.0. I think this is the latest release. Commented May 24, 2016 at 4:05
  • @JagsSparrow I know it's weird that's why I'm here. I'm thinking it might be only the debugger. Because when I'm accessing it in the browser I can see the result Commented May 24, 2016 at 4:08
  • @JonathanLonowski I added the whole code. (I removed everything except for the updated code and still got the same error) Commented May 24, 2016 at 4:10

2 Answers 2

1

I found out where it came from, the error came from the gulp-jscs. Updating gulp-jscs to 3.0.2 fixes the error.

Sign up to request clarification or add additional context in comments.

Comments

0

You can write

module.exports.controller = function (app) {
    app.get('/test', (req, res, next) => res.json('test'));
}

because arrow functions return always the result of the last expression without curly brackets.

7 Comments

You need braces for statements, and a return. You can leave off the braces if the body of the function is an expression.
@FizzyTea, it is in this case.
Yeah, the point is arrow functions don't return the result of the last statement. You need a return unless the body of the function is an expression.
@FizzyTea arrows are there for mostly inline operations like in Array methods or passing a calculated argument to a function. If you find yourself in need to use curly braces and return in an arrow then i suppose you best use proper function notation instead. Having said that at some cases i have to group the instructions with parens like. a.reduce((p,c) => (c.stg == 42 && p.push(c.stg),p),[]); so yes the last instruction gets returned in this case.
Yeah, the original wording was 'statement', and that's not a statement.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.