Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5621

Function created as var doesn't have .name property. Why?

Today at a presentation about JS, we (students) were told that in JavaScript everything is an object. As an example, this code was provided:

// functions are objects
function aFunction(a, b) {
    // do something
};

console.log(aFunction.name); // aFunction

I've found this interesting and decided to try if the function declared as var funcName = function(... will behave the same way. It doesn't:

function aFunction(a, b) {
    return a + b;
}

var bFunction = function(a, b) {
    return a + b;
};

console.log(aFunction.name); // aFunction
console.log(bFunction.name); // empty string

Why?

Upvotes: 2

Views: 151

Answers (3)

Richard Hamilton
Richard Hamilton

Reputation: 26444

That's because it's an anonymous function, it doesn't have a name. Anonymous functions calling the name property will return an empty string.

var bFunction = function bFunction(a, b) {
    return a + b;
};

alert(bFunction.name);

Upvotes: 4

Mulan
Mulan

Reputation: 135367

This is an unnamed function. Sometimes called an "anonymous" function or a "lambda".

function(a, b) {
    return a + b;
}

If you want it named, you could do

var bFunction = function bFunction(a, b) {
    return a + b;
};

But that's a bit redundant, and if you wish for your function to be named, it's best to just write it as a named function

function bFunction(a, b) {
    return a + b;
};

bFunction;       //=> function bFunction(a,b) { ... }
bFunction.name;  //=> "bFunction"

As for the comments below, the not-so-obvious benefit of using named functions is they stacktrace better. That is, if you frequently use anonymous functions in your code, and an error occurs in one of them, the stacktrace will not be too informative.

Compare the anonymous function error

(function() { undefined.x; })()

//=> Uncaught TypeError: Cannot read property 'x' of undefined at <anonymous>:2:24

Vs the named function error

(function foo() { undefined.x; })()

//=> Uncaught TypeError: Cannot read property 'x' of undefined at foo (<anonymous>:2:28)

Notice how the named function stacktrace mentions foo which helps us identify the function that contains the bug.

Upvotes: 7

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17587

Simply because you didn't assign a name to it.

var bFunction = function bFunction(a, b) {
    return a + b;
};

alert(bFunction.name); // changed to alert since it works better with the snippets

Upvotes: 2

Related Questions