Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Getting a Handle on the DOM A Simple Example

My code is exactly the same here but it doesn't work. When I open the error console it says "unexpected token ')' "

Here is my code:

const myHeading = document.getElementById('myHeading');

myHeading.addEventListener('click', () => {
  myHeading.style.color = 'red';

});

3 Answers

Seth Kroger
Seth Kroger
56,413 Points

Guil is using an arrow function here, which is a new syntax for functions in ES2015/ES6. Browser support is fairly good now (except for IE) but you could be using an older or un-upgraded browser that doesn't know about it.

Yes thank you! I was using version 9.1.3 of safari but support for arrow functions wasn't introduced until version 10. Changing to google chrome now anyway. Thanks again!

Okay so I fixed it myself but I still am confused. I changed my code to this:

const myHeading = document.getElementById('myHeading');

myHeading.addEventListener('click', function red () {
  myHeading.style.color = 'red';

});

So I gave the function a name and changed it around a bit. Now it works exactly like in the video.

So I suppose now my question is: What does Guil do here? Why does he not name the function? And how come he used =>? Especially since it didn't work at all for me.

Naming the function is not necessary when you are using it as an argument in another function, if you remove the function name "red" it will still work these functions are called "anonymous function". You might be using an older browser that's why arrow function doesn't work for you.

Ah yes you're right. I was using safari 9.1.3 and support for arrow functions only came in version 10. Thanks!