Javascript Function Name

Introduction

Javascript function names are pointers to functions.

We can have multiple names for a single function:

function sum(num1, num2) { 
  return num1 + num2; 
} 
console.log(sum(10, 10));         // 20 
                    //www . j a  v  a2  s .  co m
let anotherSum = sum;         
console.log(anotherSum(10, 10));  // 20 

sum = null;         
console.log(anotherSum(10, 10));  // 20 

Javascript 6 provides a read-only name property that returns the function name.

If a function is unnamed, it returns empty string.

If it is created using the function constructor, it returns "anonymous":

function foo() {} 
let bar = function() {}; 
let baz = () => {}; 
  
console.log(foo.name);               // foo 
console.log(bar.name);               // bar 
console.log(baz.name);               // baz  
console.log((() => {}).name);        // (empty string) 
console.log((new Function()).name);  // anonymous 

If a function is a getter, a setter, or instantiated using bind(), it returns a prefix to identify.

function foo() {}
console.log(foo.bind(null).name); // bound foo 

let person = {/*from   w ww  .j  a v a  2 s .c om*/
    years: 1,
    get age() {
        return this.years;
    },
    set age(newAge) {
        this.years = newAge;
    }
}

let propertyDescriptor = Object.getOwnPropertyDescriptor(person, 'age');
console.log(propertyDescriptor.get.name); // get age 
console.log(propertyDescriptor.set.name); // set age 



PreviousNext

Related