Lotok Lotok - 4 months ago 9x
jQuery Question

JavaScript Arrow functions understanding

I have this function:

$(".tabstrip li").each(function () {
$(this).attr("id") == "searchlist" ? $(this).addClass("selected") : $(this).removeClass("selected");

Now i was asking myself, if I can make this shorter. So I tried this:

$(".tabstrip li").each(() => $(this).attr("id") == "searchlist" ? $(this).addClass("selected") : $(this).removeClass("selected"))

And it don't worked. How I understood arrow functions this should be correct.

(There is no error too)

Do someone understand this? Its not important but I cant sleep until i figure out why this don't work ;)

Thank you for your time ^^


Arrow functions set the value of this inside them so it is the same as the value of this outside them.

This breaks your code, because a regular function called by each will have a value of this based on the current value being looped over (and your function depends on that being the case).

Do not use arrow functions "to make code shorter". That isn't what they are for. Arrow functions are for controlling the value of this.