0

// 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.

nt314
  • 29
  • 2

1 Answers1

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.

SNOSeeds
  • 116
  • 4
  • How can you can the function by the name `mul` and why does `mul(2, 3);` cause an error? – jabaa Jan 20 '22 at 20:40
  • It's a reference error caused by trying to access `mul` in the scope where it is not declared and does not exist. – SNOSeeds Jan 20 '22 at 20:56
  • This should be part of your answer with a description of the scope you can use the reference `mul`. The question is _"Why function called by function name not working when function is created by assigning it to a variable?"_ Your answer doesn't answer it. – jabaa Jan 20 '22 at 20:57
  • Thanks, @jabaa, I've edited the answer. Although, my initial answer mentioned that `mul` is not registered as a variable in the scope (where it is called). – SNOSeeds Jan 20 '22 at 21:03
  • But what is the scope? – jabaa Jan 20 '22 at 21:04