Results 1 to 3 of 3

Thread: Number() and ValueOf()

  1. #1
    Join Date
    Sep 2015

    Number() and ValueOf()

    This is a fragment from the book "Professional Javascript for Web Developers 3rd edition" :

    In the section about Number Conversions, it says:

    "When Number() function is applied to Objects, the valueOf() method is called and the returned value is converted based on the previously described rules. If that conversion results in NaN, the toString() method is called and the rules for converting strings are applied."


    Lets supose I have a "car" object.

    car.valueOf() // Object.
    So , when applying Number() to an object, what is the purpose of call the valueOf() method, If the returning value is already object. ?

    I don't get it.

    I try to convert an Object to a number, valueOf method is called, which returns object, so is the same?


    Thanks in advance!

  2. #2
    Join Date
    Mar 2007
    In Short, no, they are not the same. The simple answer is that one is an Object type and the other is a method. Try here https://www.w3schools.com/jsref/jsre...eof_string.asp to start with.

    I have lost count of the non help questions asked here that can easily be solved by reading up at a resource dedicated to the language being used.

    IMHO, you should start here : https://www.w3schools.com/js/default.asp and when you feel more confident of your understanding of JavaScript, you should take a look at the Mozilla Developers Network (MDN) web site for more technical examples of JavaScript.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Mar 2011
    You'll have to overwrite the default toString/valueOf methods. Most of the time there is a better solution than changing these.
    Ridiculous example for demonstrative purpose.
    function Dog(name, age){
     this.toString = function(){return name};
     this.valueOf = function(){return age};
    myDog = new Dog('Pluto', 8);
    console.log(String(myDog), Number(myDog));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center