Dmitri Zaitsev
Dmitri Zaitsev

Reputation: 14046

Uncaught SyntaxError: Unexpected token return - still no answer?

So there are dozens of questions with this title, however, all answers I could find seem to mention some hacks working in some specific cases but not being helpful in others. Many are concerned with jQuery or Ajax, yet the problem is pure JavaScript arising at very basic level:

function f() {
  false || (return true);
}

This function declaration (without execution) throws

Uncaught SyntaxError: Unexpected token return

in Chrome and

SyntaxError: Return statements are only valid inside functions

in Safari. However this function doesn't:

function f() {
  false || (a=true);
  return true;
}

Anybody can explain this strange behaviour?

Upvotes: 8

Views: 29093

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

You are using return statement in an expression, as an expression, which is not possible as JavaScript engine cannot evaluate it. Thats why it is throwing the error.

Upvotes: 3

elclanrs
elclanrs

Reputation: 94101

Because return is not an expression, but it expects an expression:

function f() {
  return false || true;
}

Upvotes: 5

Related Questions