Difference between two functions that run only once in javascript

Asked

Viewed 56 times

0

I looked for a script to perform a function only once and found the function below

var something = (function() {
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            alert("olá");
        }
    };
})();
<a href="#" onclick="something()">Executar</a>

Well, it works perfectly!

But I do not understand why so much code since I summarized it in this way and also works perfectly

    var executada = false;
    function chama() {
        if (!executada) {
            executada = true;
            alert("olá");
        }
    };
<a href="#" onclick="chama()">Executar</a>

Any specific reason in the first code?

  • There is someone chasing me downvoto on everything that is of my own making!! unfortunate this. What’s wrong with my question? This type of conduct does not add anything useful to the purpose of the site.

1 answer

9


The reason for these IIFE, particularly in your example, is to create a block of own scope, to have "internal variables".

Note that the variable executada In the second example, it is global and can be changed unintentionally in other parts of the code. Whereas in the first example it is local and cannot be modified from outside this IIFE.

In this first example executed is a type of memory of the function created below with return function () {, and how can not be modified outside the IIFE that is very useful.

In addition to the case you refer to in the example, you can read more examples here (in this answer).

  • 1

    Nor will I wait for another answer to decide which one to accept since the answer was given by the King of Javascript :)

  • @Leocaracciolo :) Next time you can always wait for another, there are people here who explain better than me. But I’m glad the answer answered your question.

  • I can say that in the first executed is in the lexical scope and in the second global scope?

  • 1

    @Marconi Yes, you can. "Lexical scoping" is a feature of the language, in this case it would be "global scope" and "lexical scope of the function".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.