0

For just forever, I have been wrapping page load javascript inside an anonymous function (a pattern I learned from numerous examples right here on SO) like this:

<html>

<script>

    (() => {
        // do page load stuff here.
        document.getElementById("someId").style.color = "blue";
    })();

</script>
</html>

But this does the same thing:

<html>

<script>

    // do page load stuff here.
    document.getElementById("someId").style.color = "blue";

</script>
</html>

The script is going to run regardless, so what is the point of the outer anonymous function wrapper, and when would I use one and when would I not use one?

KWallace
  • 624
  • 7
  • 15
  • If you use variables inside, you do not produce globals. – epascarello Oct 17 '22 at 15:15
  • To WHOEVER closed the question: Thanks, that's exactly what I was looking for, and explained exactly what I needed to know. If only SO's algorithm could find and suggest THOSE previously questions when creating a new question. But it never came up, and no amount of searching on my part did it. It takes someone human to make the connection between "self executing" and "anonymous". So, thanks again. Should I just delete this question? – KWallace Oct 17 '22 at 18:52

0 Answers0