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

221
Visualizações
Why function called by function name not working when function is created by assigning it to a variable?

// I created two function in JavaScript

// **Function 1**

function add(a, b) {
  return a + b;
}

// To call above function I use and it worked as expected
add(2, 3);




// **Function 2**

let x = function mul(a, b) {
  return a * b;
}

// To call above function I use two ways
x(2, 3);

mul(2, 3); // This won't work. Why?

Why the mul(2,3); throwing an error?

mul(2,3) is the name of the function, it should be used to call the function.

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

0

This shows you that in JavaScript, functions are also first-class values. In the add function you have up there, the name of the function: add, is actually a variable that a function definition is stored inside of it. For the second example, mul is not registered as a variable in the scope (list of variables) in the program's memory, rather, what you have there is a function expression, wherein you assign a function definition or say function value to a variable that is x in your case, omitting the mul in that function definition is in fact valid.

The error from calling mul is caused by trying to access mul in the scope (appears to be global) where it is not declared and is neither accessible from other scopes the global scope can access.

Scope (available variables to a program's memory) exists at different levels in JavaScript, two of which are global scope and function scope.

Within the scope of the mul function, mul is accessible there, as well as other variables in a scope that is at a higher level like add (present in global scope) because inner scopes can access outer scopes.

Whereas, mul as well as other variables declared within it cannot be accessible outside of mul's function scope, because outer scope cannot access inner scope.

The inner scopes in your snippet are those of add and mul function scopes, while the outer scope appears to be a global scope.

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