Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this JavaScript syntax supported in Google Chrome?

I initiated a JavaScript/jQuery click listener like this:

$("#test").on("click", () => {
   console.log("test");
});

This piece of code works perfectly fine in Firefox but in Chrome this seems to give me a Syntax error. Why is this, since this looks like 'ok' syntax to me.

You can test this quickly in the console by doing

 var a = () => {return 0;}
 a();

In Firefox 27.0.1 this returns 0 In Chrome it returns SyntaxError: Unexpected token )

like image 711
Biketire Avatar asked Feb 18 '14 14:02

Biketire


People also ask

Why is my JavaScript code not working in Chrome?

Google ChromeIn the "Settings" section click on the "Show advanced settings..." Under the the "Privacy" click on the "Content settings...". When the dialog window opens, look for the "JavaScript" section and select "Allow all sites to run JavaScript (recommended)". Click on the "OK" button to close it.

Is JavaScript working on Chrome?

How do I know if JavaScript is working on Google Chrome? On Google Chrome, JavaScript is enabled by default, but you can verify if it works through the Settings menu. To reveal the Settings menu, simply click on three tiny black dots at the top-right corner of your Chrome window.


1 Answers

The fat arrow is a feature of ES6 (now officially called ECMAScript 2015). It's been introduced in Firefox but not yet in other browsers (and especially not completely in V8 which would be interesting for nodejs/iojs development).

As it's mostly sugar, you'd better wait before using it.

If you need the scope binding (this is the same in the function call and in the scope in which the function was defined, we speak of "lexical this"), then instead of

$("#test").on("click", () => {
   some code
});

you can simply do

$("#test").on("click", (function() {
   some code
}).bind(this));

If you don't (as in your example), then simply do

$("#test").on("click", function() {
   console.log("test");
});
like image 79
Denys Séguret Avatar answered Oct 20 '22 00:10

Denys Séguret