Mark Mark - 1 year ago 121
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)

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
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download