Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How useful is Function.name property? [closed]

Tags:

var func1 = function() {}
console.log(func1.name); // func1

Is there any real-time usage of this property from the javascript developer's perspective?

like image 671
Prem Avatar asked Mar 21 '18 07:03

Prem


People also ask

Why function closure is important?

Closures are important because they control what is and isn't in scope in a particular function, along with which variables are shared between sibling functions in the same containing scope.

What are the advantages of using closure?

Pros. Closure allows us private variables that are available even after a function task is finished. Closure enables us to store data in a separate scope and share it only where necessary.

What is the purpose of a function name?

The function's name property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. To change it, use Object.

Are closures functional?

No, closures do not cause a function to be impure, as long as the closed value is constant (neither changed by the closure nor other code), which is the usual case in functional programming.


2 Answers

You can use it for debugging purposes when you pass function as a parameter to another function, for instance:

var fun1 = function(){};

function fun2(){};

var g = function(f){
    console.log("Invoking " + f.name);
    f();
}

if(Math.random() > 0.5){
    g(fun1);
} else {
    g(fun2);
}
like image 96
mickl Avatar answered Sep 19 '22 12:09

mickl


The answer to this question will be quite broad, since there are hundreds of examples for the usage of property called name. They are covered in detail in JavaScript documentation. Few of the examples are following.

Changing the function name.

var newName = "xyzName";
var f = function () {};
Object.defineProperty(f, 'name', {value: newName});
console.log(f.name); // will output xyzName

For logging the class stack we can get the constructor name as in the following example.

function a() {};
var b = new a();
console.log(b.constructor.name); // will output a

Get the function name if it's not anonymous.

var getRectArea = function area(width, height) {
    return width * height;
}
getRectArea.name; //will output area
like image 27
Syed Waqas Bukhary Avatar answered Sep 21 '22 12:09

Syed Waqas Bukhary