Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+ operator in Javascript

Tags:

javascript

So I've noticed that the result of

(new Date())

is a Date object; in this case

Date {Thu Dec 04 2014 22:43:07 GMT+0200 (SAST)}

but if I type

+(new Date())

I get an int value;

1417725787989

How is this done?

I have a function called 'Duration' which, when used like this:

new Duration(352510921)

returns an instance looking like this:

{ days:5, hours:3, mins:55, secs:10, ms:921 }    

So how can I use the + operator to get the int value of the Duration instance?

var dur = new Duration(352510921);
console.log(+dur) // prints int value 352510921
like image 796
Gavin van Gent Avatar asked Feb 12 '23 10:02

Gavin van Gent


1 Answers

The unary + operator casts the instance to a Number in the same way that calling the Number() function will cast a variable to a Number.

If you'd like to override how your specific instance is cast, you need to override the valueOf property for that instance:

var a = {
    valueOf: function () {
        return 5;
    }
};
console.log(a); //Object { valueOf: function () {...} }
console.log(+a); //5

From the ES5 standard:

11.4.6 Unary + Operator # Ⓣ Ⓡ Ⓖ

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).

ToNumber on an Object will then result in a ToPrimitive with hint Number. ToPrimitive will then call the [[DefaultValue]] internal method which states:

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:

  1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
  2. If IsCallable(valueOf) is true then,
    1. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
    2. If val is a primitive value, return val.
  3. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
  4. If IsCallable(toString) is true then,
    1. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
    2. If str is a primitive value, return str.
  5. Throw a TypeError exception.
like image 102
zzzzBov Avatar answered Feb 13 '23 23:02

zzzzBov