picking arrow functions vs regular functions

Hey, i understand that picking whether to use arrow functions or regular functions is sometimes based off of preference but mainly based off of what behavior you'd like, however why are functions such as setTimeout mainly seen to use arrow functions not regular? e.g.
setTimeout(() => {
console.log("xyz");
}, 1000);
//not
setTimeout(function() {
console.log("xyz");
}, 1000);
setTimeout(() => {
console.log("xyz");
}, 1000);
//not
setTimeout(function() {
console.log("xyz");
}, 1000);
at first glance, there doesn't seem to be any more benefits to one than the other in this case so is this more of a personal preference one? thanks in advance.
15 Replies
Jochem
Jochem7d ago
I use them cause they're shorter
13eck
13eck7d ago
I use them because of the implicit return
lko
lko7d ago
The only difference i think is that you can return stuff more easily with arrow function, for example
() => "hi"

function example() {
return "hi"
}
() => "hi"

function example() {
return "hi"
}
Jochem
Jochem7d ago
also a very good reason
13eck
13eck7d ago
I do more functional programming so a short, one-line function with implicit return is almost always preferable for me
Jochem
Jochem7d ago
though with setTimeout I find myself often just writing the function and passing it in by reference single line implicit returns are something I use more with array functions like map or sort or filter
13eck
13eck7d ago
And when using curried functions it doesn’t look as cluttered:
const pipe = (…fns) = (data) => fns.reduce( (d ,fn) => fn(d), data);
const pipe = (…fns) = (data) => fns.reduce( (d ,fn) => fn(d), data);
snxxwyy
snxxwyyOP7d ago
ah okay that makes sense, i appreciate everyone's opinions
13eck
13eck7d ago
Keep asking questions, I always have opinions! lol
snxxwyy
snxxwyyOP7d ago
i'll keep that in mind haha
ἔρως
ἔρως7d ago
i always prefer using the old-school variant because you can hoist and name them for debugging, a named function is amazing for example:
form.addEventListener('submit',
function click_handler(e) {
e.preventDefault();
[...]
});
form.addEventListener('submit',
function click_handler(e) {
e.preventDefault();
[...]
});
this means that, when you run the code and something bad happens, you will see click_handler instead of <anonymous function>
snxxwyy
snxxwyyOP7d ago
ah yeah that seems useful, can't you name arrow functions by putting them in a variable though?
ἔρως
ἔρως7d ago
that's not a named function it's still an anonymous function
snxxwyy
snxxwyyOP7d ago
ah okay
Choo♚𝕂𝕚𝕟𝕘
My IDE offers an arrow function in the autocompletion whenever a callback is needed, so it's easier to just use that instead of deliberately overriding the suggestion.

Did you find this page helpful?