1

I'm puzzled by something in my js. Normally I define functions like this:

function f(){
    // do stuff
}

but I can also define functions like this:

f = function(){
    // do stuff
}

I always thought there is no difference between them, but I now found that this is working:

f = function(){
    alert('IT WORKS!!');
}

function createCallback(request){
    request.done(function(data){
        var html = '';
        data['result'].forEach(function(bill){
            html += "<tr onclick=\"f();\"><td>" + bill.title + "</td></tr>";
        });
        $("#someId").html(html);
    });
}

but when I define f as follows:

function f(){
    alert('IT WORKS!!');
}

and I click on the row, it gives a ReferenceError: f is not defined.

So I wonder: what is actually the difference between function f(){} and f = function(){}?

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
kramer65
  • 39,074
  • 90
  • 255
  • 436
  • 2
    I suggest to read http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Nehal Jan 24 '15 at 11:59

2 Answers2

7

When you define a function without using var statement, by default the function will be defined as a property in the global scope.

Quoting MDN documentation on var,

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:

  1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

  2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.

  3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

So, when you define with function function_name(...){...} syntax, it will be in the current scope.

Since the second function definition is in the global scope tr's onclick can find f. Try using var statement like this

var f = function(){
    alert('IT WORKS!!');
}

you will get the same ReferenceError: f is not defined.

Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
2

You forgot the var statement. The function is defined globally when using f = function(){ }. This is why it’s accessible from the onclick handler and the other is not.

Please also read var functionName = function() {} vs function functionName() {} as suggested by @Nehal.

Community
  • 1
  • 1
aaronk6
  • 2,345
  • 1
  • 16
  • 24