3

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

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

I am little confused with javascript named function. Can any one please explain why in above code snippet the foo() function call is throwing the error. Thanks in advance

Indranil
  • 57
  • 4
  • You're *naming* the function `foo`, but that doesn't mean a variable `foo` is going to be created for it. – deceze Aug 04 '17 at 07:28
  • 1
    var boo= function(){ console.log("I am foo"); } . You can set javascript naming function like this. – Sanil Aug 04 '17 at 07:28
  • really i didnt expect the code to work it should read var boo = function(){...}; the assignment expects an anonymous function. – jidexl21 Aug 04 '17 at 07:29
  • The scope of the names of [named function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#Named_function_expression) (different from function *declarations*) is inside the functions themselves. – Ry- Aug 04 '17 at 07:29
  • `foo` in your code is inline function and its scope isn't global. You can change to `function foo() {} var boo = foo;` – huydq5000 Aug 04 '17 at 07:30
  • Take a look at this question https://stackoverflow.com/a/338053/1653117 – Farnabaz Aug 04 '17 at 07:34
  • 2
    @deceze I slightly disagree with the duplicate. Looks like OP knows what is named function expression and his actual question is why one cannot invoke function with its name while using named function expression. Correct me if I am wrong. – Suresh Atta Aug 04 '17 at 07:37
  • @ꜱᴜʀᴇꜱʜᴀᴛᴛᴀ I think between those *two* duplicates this is reasonably well answered, no? – deceze Aug 04 '17 at 07:41

1 Answers1

1
var boo= function foo(){

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

What you have is an expression resolved to a variable. The way you are expecting to work needs to be a function or a variable resolved by a function expression.

From MDN docs

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

var myFunction = function() {
    statements
}

It is also possible to provide a name inside the definition in order to create a named function expression:

var myFunction = function namedFunction(){
    statements
}

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

As we can see, both example do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

Ry-
  • 199,309
  • 51
  • 404
  • 420
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284