Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token ) when using void()

Tags:

javascript

I get this error and I've managed to narrow it down to:

<a href="javascript:void();" onclick="myFunction();">aaa</a>

That line of code is now the only thing in my source code and still I get the error in title. Any idea why so?

Even when surrounded with the appropriate HTML elements (html, head, body etc) I am still thrown the error. The error shows up in Chrome dev console and via alert if I include a

window.onerror

function in the head tag. It also occurs when the myFunction() method actually exists. As far as I can gather, there is absolutely nothing wrong with that above statement whatsoever.

like image 469
PsychoMantis Avatar asked Jul 28 '13 17:07

PsychoMantis


People also ask

What is uncaught SyntaxError unexpected token?

The error Uncaught SyntaxError: Unexpected token < is most commonly caused by your site's code referring to an asset that is no longer available. Most commonly, this is due to a filename change in assets generated during your build.

What is uncaught SyntaxError unexpected identifier?

The "Uncaught SyntaxError: Unexpected identifier" error occurs for 2 main reasons: Misspelling a keyword, e.g. Let or Class instead of let and class . Having a typo in your code, e.g. a missing or extra comma, parenthesis, quote or bracket.

What is JavaScript token?

Tokens: These are words or symbols used by code to specify the application's logic. These include +, -, ?, if, else, and var. These are reserved by the JavaScript engine and cannot be misused. They also cannot be used as part of variable names.


3 Answers

Use

<a href="javascript:void(0);" onclick="myFunction();">aaa</a>

void expects a parameter.

There's an interesting discussion on using void(0) or other techniques here.

like image 107
keyboardP Avatar answered Oct 02 '22 02:10

keyboardP


Is because void takes one argument. You want:

<a href="javascript:void(0);" onclick="myFunction();">aaa</a>
like image 39
lorenzo Avatar answered Oct 02 '22 04:10

lorenzo


void is an operator, not a function. It requires a single expression as its operand. () is not a valid expression. The correct syntax is:

<a href="javascript:void 0;" onclick="myFunction();">aaa</a>

You can put parentheses around 0, but they're not necessary, just as you don't need parentheses around 0 when writing 3 + 0.

like image 31
Barmar Avatar answered Oct 02 '22 04:10

Barmar