Javascript named function call throwing error

var boo= function foo(){
  console.log("I am foo");
}

boo(); // output: I am foo
foo(); // output: Uncaught ReferenceError
      

Run codeHide result


I am a little confused by the named javascript function. Can someone explain why, in the above code snippet, calling foo () is throwing an error. thanks in advance

+3


source to share


1 answer


var boo= function foo(){

      

There is a clear distinction between a function expression and a function expression.

You have an expression resolved to a variable. The way you expect to work should be a function or variable resolved by a function expression.



From MDN docs

Below is an example of an anonymous function expression (name not used):

var myFunction = function() {
    statements
}

      

It is also possible to specify the name inside the definition in order to create the function name of the function:

var myFunction = function namedFunction(){
    statements
}

      

One of the advantages of creating a named function expression is that in the event we encounter an error, the stack trace will contain the function name, making it easier to find the source of the error.

As we can see, both examples do not start with the function keyword. Function-related statements that do not start with a function, function expressions.

+1


source







All Articles