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 trialMuhammad Haris Khan
8,587 PointsWhy are you not using arrow function instead for this?
Can you give an example using arrow functions?
2 Answers
Ken Howard
Treehouse Guest TeacherMuhammad Haris Khan - arrow functions aren't necessary in the example used in this video. You can continue to use regular functions as you might have previously used them.
However, there isn't much difference in the syntax except you'll assign the anonymous function to a variable as demonstrated here.
const sayHello = (greeting = 'Hello', name = 'Muhammad') => {
return `${greeting} ${name}`;
}
console.log(sayHello()); // "Hello Muhammad"
console.log(sayHello('Hi', 'Ken')); // "Hi Ken"
Thomas Nilsen
14,957 Points//Arrow function
var sum = (a,b) => {
return a + b;
};
//Regular function expression
var sum = function (a, b) {
return a + b;
}
Muhammad Haris Khan
8,587 PointsMuhammad Haris Khan
8,587 PointsIf one is using ES6 syntax in the application, is it a good practice to deviate and write non arrow functions, in short when is it necessary to use arrow function, or is it simply a matter of taste? Thanks!
nico dev
20,364 Pointsnico dev
20,364 PointsSorry, I know it's a little late for this, but better late than never, and anyway I am try to confirm it to myself. :)
Correct me if I'm wrong, but I think the function used in this video was only used for an example. However, in actual JS that you use within the context of a more complex app (this one would just print a greeting, and it wouldn't make sense, it was only created for demonstration purposes), you would use arrow functions for callbacks or otherwise you would name them with a const as shown above. But none of those cases seem to make a lot of sense in the example's demonstration, I think.
Now, imagine you use this function about printing the greeting in a website. Well, maybe you'll rather use it as a callback for an event listener. In that case, yes, it would make sense to just use the arrow function as a callback inside the event listener.