2

I have noticed the snippet_1 in the implementation of one of the Node API's. Snippet_2 has been written by me. I don't feel much difference between them. Is there really any significance of using valueOf() function. And also, we can notice a property called as valueOf which would return [Function: valueOf]

Snippet_1

Buffer.from = function from(value, encodingOrOffset, length) {
    const valueOf = value.valueOf && value.valueOf();
      if (valueOf !== null && valueOf !== undefined && valueOf !== value)
        return Buffer.from(valueOf, encodingOrOffset, length);

}

Snippet_2

Buffer.from = function from(value, encodingOrOffset, length) {
  if (value !== null && value !== undefined)
    return Buffer.from(value, encodingOrOffset, length);

}
Prem
  • 5,685
  • 15
  • 52
  • 95
  • What happens in the else case? Can you please link the implementation where you found this for some context? – Bergi Sep 15 '17 at 09:23
  • It really should have been `const valueOf = typeof value.valueOf == "function" ? value.valueOf() : null`, otherwise this fails on objects with custom `valueOf` data properties. – Bergi Sep 15 '17 at 09:24
  • "*I don't feel much difference between them.*" - Isn't the difference obvious? The two snippets do very different things. Do you really think they have the same outcome on all possible values? – Bergi Sep 15 '17 at 09:25
  • @Bergi : https://github.com/nodejs/node/blob/8f52ccc828c26aee8fe78c82a8a23fabd21918b7/lib/buffer.js#L161 – Prem Sep 15 '17 at 09:28
  • Well the check in your proposed implementation is unnecessary since [that case](https://github.com/nodejs/node/blob/8f52ccc828c26aee8fe78c82a8a23fabd21918b7/lib/buffer.js#L196) is always true. – Bergi Sep 15 '17 at 09:33
  • Now when that is the only code in a function it even makes less sense. – Bergi Sep 15 '17 at 09:35

1 Answers1

2

If you have an object wrapper and you want to get the underlying primitive value out, you should use the valueOf() method. This is called Unboxing.

All normal objects have the built-in Object.prototype as the top of the prototype chain (like the global scope in scope look-up), where property resolution will stop if not found anywhere prior in the chain. toString(), valueOf(), and several other common utilities exist on this Object.prototype object, explaining how all objects in the language are able to access them.

Assume the following example:

var i = 2;

Number.prototype.valueOf = function() {
    return i++;
};

var a = new Number( 42 );

if (a == 2 && a == 3) {
    console.log( "Yep, this happened." );
}

Will this behave the same way with your snipper? The answer is no.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31