-1

Why does the following piece of code not define the dummy function?

if(function dummyFunction() {}){

}
console.log(dummyFunction); // Throws ReferenceError: dummyFunction is not defined

The reason why I ask is - had I defined it as following -

function dummyFunction(){}
console.log(dummyFunction); //This would have worked

BUT:

var xxx = function dummyFunction(){}
console.log(dummyFunction); //This would NOT have worked.

Somehow I feel that when I use it with if condition, it should have behaved like the first case and not the second. I fail to understand why without assignment to a variable (like in the second case) I am not able access the method via function name.

Update: I got to face this problem when I was solving a JS questionnaire.

tusharmath
  • 9,120
  • 11
  • 52
  • 70
  • 3
    [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) may help explain. Function *Expressions* don't attach their name to the surrounding scope like *Declarations*. – Jonathan Lonowski Jul 15 '14 at 06:30
  • Because that's a function expression, not a function definition. – JLRishe Jul 15 '14 at 06:30

2 Answers2

4

When you put the function definition in the if(), it's a named function expression. The scope of the name is just the body of the function, not the surrounding scope. It's analogous to:

var foo = function dummyFunction() {};

This defines foo in the outer scope, but dummyFunction is only defined in the body of the function.

I'm not sure why you're doing this, but the way to write it is:

if (var dummyFunction = function() {}) {
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I would say there is no way to correctly write whatever it is OP is trying to do. – JLRishe Jul 15 '14 at 06:36
  • I don't get it why is it `named function expression`, is there some other place also where we observe the same kind of behavior? – tusharmath Jul 15 '14 at 07:07
  • It's a named function expression because it's a function expression and it has a name after the `function` keyword. The keyword `function` only starts a function **definition** if it's at the beginning of a statement. – Barmar Jul 15 '14 at 07:08
  • Did you read the linked question, it explains all the different ways to define functions. – Barmar Jul 15 '14 at 07:08
0

Like this?

var dummyFunction;
if(typeof dummyFunction !== 'Function'){
  dummyFunction = function(){}
}
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187