What case is better to use function or with arrow function?

<button id="b1">function</button>
<p>
<button id="b2">arrow function</button>

$("#b1").click(function () {
    $("li").each(function () {
        console.log(this);
    });
});

$("#b2").click(function () {
    $("li").each(() => console.log(this));
});

Because this do what they get. But for this example is matter what to use? then how decide what to use exactly? normal function or iwht arrow function? Like for a click event is need with arrow function or with a normal one?

$("button").click(() => {
     $("<h1>Hello World!</h1>").replaceAll("h2");
});
$("#button").click(function () {
     $("<h1>Hello World!</h1>").replaceAll("h2");
});     

Is do the same the click then from choice what? Is not clear for me :x:

Thanks!

Arrow functionds do not bind their own this. They inherit it from the parent scope. In this case, this refers to the button element (being clicked). You can specify parameters for the each call back method though.

$("#b2").click(function () {
    $("li").each((index, elem) => console.log(elem));
});
2 Likes