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 Select a Page Element By Its ID

Domenick D'Agostino
Domenick D'Agostino
9,455 Points

What is the => function used for?

I understand it is making a function, what I am confused about is why we are using the arrow rather than writing function? Is this just a shorthand or is there a difference I should take notice of?

3 Answers

Steven Parker
Steven Parker
231,268 Points

It is a shorthand notation for creating functions, but there are also some differences that you should be aware of. One of the most important differences is that an "arrow function" does not create a "this" like conventional functions do.

A complete discussion of the differences can be found on this MDN documentation page.

Domenick D'Agostino
Domenick D'Agostino
9,455 Points

Awesome, thank you so much for the response.

david mchale
david mchale
1,434 Points

Be nice if the most common syntax was used as most online tuts use the same methods for teaching. I know the new ECMA script uses const and let etc, but it makes it really confusing when trying to code simple programs as a beginner when different variations are used. Even the introduction to JS on treehouse uses var, not let or const. As with Dominic above, using () => when we could use the same as most explanations. As with CSS, we can do shorthand when we get up to speed using JS confidently.

var myHeading = document.getElementById('myHeading'); var button = document.getElementsByTagName('button')[0];

function clickMe(){ return myHeading.style.color = 'red'; }

button.addEventListener('click', clickMe, false);

Tyler Durden
Tyler Durden
2,406 Points

I agree, I watched basic JS tutorials and watched the ES2015 tutorials so I knew about the arrow function, but I was re-writing JS functions I wrote for my personal website to arrow notation, and it wasn't working.

I read the above post where Steven stated it doesn't create "this" and now have concluded thats why the arrow notation was working for me, because I was essentially looping (via for loop) through a class of <divs> and "listening" (via mouseover) for a mouse over event , and then I would use this. to get a next elementsibling of "this".

Well atleast i know now