Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
JavaScript: What is the difference between function f(){} and constant f =(function(){...})()?

Here are two ways of writing a function that includes an IIFE:

    function f() {
        let count=0;
        return function() {
            return ++count;
        }
    }

    const g = (function() {
        let count=0;
        return function() {
            return ++count;
        }
    })();

f() returns function () { return ++count; }

When g() is run several times, it returns 1, 2, 3... which is the intention.

Now another example:

    function f() {
        return "This is f()";
    }

    const g = (function() {
        return "This is g()";
    })();

In this case f() returns "This is f()" and g() is a script error.

I've done a lot of coding in C-ish languages, but am new to JavaScript. What am I missing?

In response to the first answer, here is an executable code snippet. If function f(){...} were the same as const f = (function () {...})() I would expect both to run. They do not.

function f() {
    return "This is f()!";
}

console.log(f());

const h = f;

console.log(h());

const g = (function() {
  return "This is g()";
})();

console.log(g());

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Functions in JavaScript are first class objects, meaning you can treat them as any other object in JavaScript.

function f (){} is regular function definition, which you can also write as

let f = function(){}

(function{})() is basically the same as

let f = function () {}
f = f() // You reassign f to be the return value from the function that f was assigned to

You bottom case const g = (function() {return "This is g()";})(); can be written as:

let g = function() {
    return "This is g()"
}
g = g() // You are reassigning g to be "This is g()"

// Trying to call g again is like calling a string
// and it should return an error saying that g is not a function
g()

Update

There difference in your extended example is that f is a function that returns a function (always), while g immediately gets assigned to the inner "regular function", and return numbers.

function f() {
    let count = 0;
    // --- Will always return this, a function ----
    return function () {
        return ++count;
    }
    // --------------------------------------------
}

const g = (function () {
    let count = 0;
    return function () {
        return ++count;
    }
})() // <--- Here you call the (function () {}) immediately, thus you assign g to the inner returned function

console.log(f);
console.log(f()); // returns a function
console.log(g); 
console.log(g()); // returns a number
console.log(g());
console.log(g());
console.log(g());

To make f equivalent to g you have to do this:

function f() {
    let count = 0;
    return function () {
        return ++count;
    }
}
f = f() // Here
about 4 years ago · Juan Pablo Isaza Relatório

0

The behavior of the following snipped clarifies my question...

And I think I see the answer. In the first case, f() doesn't do anything until it is called. And when it is called it returns the string.

In the second case, (function(){})() executes immediately, and returns the function itself.

Like the name says, Immediate execution. Thanks for helping me ask the right question.

function f() {
        let count=0;
        return function() {
            return ++count;
        }
    }

const g = (function() {
        let count=0;
        return function() {
            return ++count;
        }
    })();
    
 console.log(f);
 console.log(f());
 console.log(g);
 console.log(g());
 console.log(g());
 console.log(g());
 console.log(g());

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda