Home > Net >  Is there difference between Number() and Number().valueOf()
Is there difference between Number() and Number().valueOf()

Time:09-28

I've come across an example which tries to check if number is part of a particular range using following code:

class RangeValidationBase {
  constructor(private start: number, private end: number) {}
  
  protected RangeCheck(value: number): boolean {
    return value >= this.start && value <= this.end;
  }
  
  protected GetNumber(value: string): number {
    return new Number(value).valueOf();
  }
}

what is the use of using new Number().valueOf() instead of Number()? and are there any cases where using new Number().valueOf() is preferred over the other as they both seem same to my noobie brain?

CodePudding user response:

what is the use of using new Number().valueOf() instead of Number()?

None. Their behaviour is the same for all inputs, other than the technicality that Number or Number.prototype.valueOf could be replaced in a bad environment, which probably makes the new Number option harder to optimize for engines and therefore slightly less efficient in practice.

are there any cases where using new Number().valueOf() is preferred over the other

No, except in some misguided in-house style. There are good reasons to prefer a simple Number(value):

  • the aforementioned behavior technicality

  • It’s good practice to avoid primitive wrapper types like the one produced by new Number(), because they don’t behave close enough to primitives to be more useful than a plain object that contains a number property (for example), and are generally confusing. Even though the wrapper is immediately discarded in this case, it’s a red flag, picked up by both humans and linters.

  • Related