Mark Mark - 4 months ago 14
Javascript Question

Javascript division on Lodash Wrapper object

I recently upgraded to Lodash 3.10.1 and I noticed something odd.

Say I have an array of numbers and I want to get the maximum in the array then half it:

var series = [ 6, 8, 2 ];

var highestTotal = _.chain(series)
.max();

console.log('highestTotal is ', highestTotal);

var halved = highestTotal / 2;

console.log('halved is ', halved);


I would have thought this would have thrown an error as
highestTotal
is a Lodash Wrapper. I.e. I would havbe thought it's necessary to do:

var halved = highestTotal.value() / 2;


For it to work. But its not! How is this happening?

Jsfiddle is here.

Iso Iso
Answer

That’s because lodash wrapper object expose a .valueOf method (which is aliased to .value) and automatically called by JavaScript when a primitive value is expected (e.g. within an arithmetic operation).

From the MDN:

function myNumberType(n) {
    this.number = n;
}

myNumberType.prototype.valueOf = function() {
    return this.number;
};

myObj = new myNumberType(4);
myObj + 3; // 7