Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • toString() Method in javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 223
    Comment on it

    Basically toString ( ) method is used to convert a number into a String .In this there is no argument .

    Syntax

    Obj.toString ( )
    

    Simple Example -

    var number = 15 ;
    var no = num.toString ( ) ; // Output -> 15
    

    Every Object has a toString ( ) method which is automatically called when the object is represented as a text value . And this method is inherited by every Object . If you do not override this method by your method (custom method) then it return ' [ Object type ]' .
    Example ->

    var obj = new Object ( ) ;
    obj.toString ( ) ; // Output : [ Object Object ] ....because you did not override by you custom method 
    

    How to override the this method ( toString ) .
    Example ->

    function student ( name , age , id , sex ) {
    this.name = name ;
    this.age = age ;
    this.id = id ;
    this.sex = sex ;
    }
    stu = new student ( ' Mukesh ' , ' 23 ' , ' 1 ' , ' Male ' ) ; 
    

    If you call toString ( ) method in this custom object , then it return the default value which is inherited from Object . i. e

    stu.toString ( ) ; // Output : [ Object Object ]
    

    If you want to override this method then you can do by making function ,see below

    student.prototype.toString = function studentToString ( ) {
    var information = ' student ' + this.name + ' age is ' + this.age + ' and id is ' + this.id + ' and gender is ' + this.sex ;
    return information ; // Output : Mukesh age is 23 and id is 1 and gender is Male 
    

    Another use of toString ( ) -> Using toString ( ) to detect object class
    Example >
    var str = Object.toString ; str.call ( new Date ) ; // Output - [ Object Date ] str.call ( new String ) ; // output - [ Object String ]

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: