Welcome Back, amazing people๐๐ผ
I am Aryan Sharma & 'm back again with a new blog of our JavaScript Blog series.
This Article is all about Using "objects as primitives"
Let's start this amazing concept in JavaScript...๐๐ผโโ๏ธ
Before moving ahead withthe topic, understand what are Primitives and Objects?
Primitives in JavaScript are immutable and represent simple data types,
while objects are mutable and can encapsulate complex structures and behaviors, making them fundamental for building more sophisticated applications.
Now, what if we add objects obj1 + obj2
, subtracted obj1 - obj2
or printed using alert(obj)
?๐ค
In case of such operations, objects are auto-converted to primitives, and then the operation is carried out over these primitives and results in a primitive value.
Thatโs an important limitation: the result of obj1 + obj2
(or another math operation) canโt be another object!
So, we have some things to keep in mind:
It will help us to comprehend what is going on in the event of a coding error or an inadvertent action.
There are several cases where such operations are both possible and desirable. Example: subtracting or comparing dates (Date objects). We will come upon them later.
Understanding Object to Primitive Conversion
In JavaScript, Object to Primitive Conversion is the process by which an object is automatically converted into a primitive value (like a string, number, or boolean).
This covert transformation is orchestrated by the internal [[ToPrimitive]]
method, which each object can define.
To put it simply, when you try to use an object in a way that expects a primitive value, JavaScript performs the conversion behind the scenes, making the interaction smooth and intuitive.
ThevalueOf
andtoString
Methods
Object to Primitive Conversion is possible only with theuse of two methods.
valueOf
valueOf(): This method returns the primitive value of the object.
toString()
toString(): If the
valueOf
method doesn't provide a suitable primitive or if it's absent, JavaScript falls back to thetoString
method.
Example:
const customObject = {
valueOf() {
return 42;
},
toString() {
return 'Custom Object';
}
};
console.log(customObject + 10); // Output: 52
Coercion in Action
Coercion has important role in understanding the Object to Primitive Conversion.
Type coercion is frequently used in JavaScript to ensure that different data types communicate smoothly.
const customObject = {
valueOf() {
return 40;
},
toString() {
return 'Custom Object';
}
};
console.log(customObject == 'Custom Object');
Here, the object is coerced into a string for the equality check, utilizing the toString
method.
Amazing tricks on this:
We can customize the valueOf
and toString
methods. By doing so, we can relate it with the JavaScript Ecosystem.
const customDate = {
valueOf() {
return new Date().getTime();
},
toString() {
return new Date().toDateString();
}
};
console.log(customDate + 1000); // Output: Current timestamp + 1000
Summary
Many built-in methods and operators that expect a primitive as a value do the object-to-primitive conversion automatically.
Some of the built-in methods are:
"string"
(foralert
)"number"
(formathematical calculations
)"default"
(few operators, same as "Number
")