Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
When a function has a name and when has no name?

When adding a new method to an object through a method the function has no name (anonymous), and when writing a new method for an object in the code, the function has a name. Why does it happen this way?

let calc = new Calculator;

//console.log( calc.calculate("3 + 7") );

let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);


let result = powerCalc.calculate("2 ** 3");
//console.log( result );

console.log(powerCalc.methods["+"].name); // has a name
console.log(powerCalc.methods["*"].name); // has no name

function Calculator () {

  this.methods = {
    "-": (a, b) => a - b,
    "+": (a, b) => a + b,
  };

  this.calculate = (str) => {
    let split = str.split(" "),
        a = Number(split[0]),
        operator = split[1],
        b = Number(split[split.length-1]);

    if (!this.methods[operator] || isNaN(a) || isNaN(b)) return NaN;
    
    return this.methods[operator](a, b);
  }

  this.addMethod = (operator, method) => {
    this.methods[operator] = method;
  }

}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When the value of a property in an object literal is an anonymous function, the property name is automatically added as the name of the function.

This is done because this is a common way to define object methods, so the property name is automatically used as the name of the method function.

It doesn't happen if the function is defined outside the object literal and later assigned to a property. You could do that yourself in the addMethod() method:

  this.addMethod = (operator, method) => {
    this.methods[operator] = method;
    if (!method.name) {
      method.name = operator;
    }
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!