object conversion

6 0 0
                                        

1. All objects are true.

2. Object use as a key will be converted to string and will function normally as ordinary object with a string key. If that key has a numeric value, then, that object key will be converted to a number.

3. When using windows such as alert(), the object is automatically converted to strings.

=================

let obj1 = {

    name: "My name"

};

function displayObjectAsString(){

     alert("This is an " + obj1);

}

================

HTML

displayObjectAsString()

Result: (Pop up window)

This is an [object Object]


4. The object like Date() object has functions that you can access and that will usually return a primitive like string. And if use in an operation, that string will be converted to a numeric and will perform the operation.

====================

let object1 = Date();

let yearToday = object1.substring(11, 15);

let object2 = {

    name: "Bucks Nets",

    yearBorn: 1970,

    (Symbol.toPrimitive](hint){

        return hint == "string" ? this.name : this.yearBorn;

    }

};

let answer = yearToday - (+object2);

function displayingMyAge(){

    document.write('${yearToday} - ${+object2} = ${answer}');

}

====================

HTML

displayingMyAge()

Result:

2022 - 1970 = 52


Using the methods below:

1. Symbol.toPrimitive - is used in the above code but it is the same with toString or valueOf().

2. toString or valueOf()

let object2 = {

    name: "Buck Nets",

    age: 1970,

    toString()

        return this.name; 

    },

    valueOf(){

        return this.age;

    } 

}



Javascript ProgrammingWhere stories live. Discover now