Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Objects in Javascript
3.
Primitives in Javascript
4.
Conversion Rules
5.
Object to Number Conversion
6.
Object to String Conversion
7.
toString and valueOf
8.
Operator Conversions
9.
Frequently Asked Questions
9.1.
What is an Object in JS?
9.2.
Is an object a primitive data type?
9.3.
Why does JavaScript store almost everything in objects?
9.4.
What is the Prototype in JS?
9.5.
How do you check if it is a number in JavaScript?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Converting Object to Primitives in JavaScript

Author Sagar Mishra
0 upvote

Introduction

Hey Ninjas! While programming in Javascript, have you ever thought about how the object gets converted into a primitive? No? Then you are at the right place. You will get all your answers related to the object and primitive in this blog.

Converting Object to Primitives in JavaScript

This blog will discuss the topic of Object to Primitive Conversion in Javascript. But before moving ahead, do you know what objects are? Let's take a quick revision on this.

Also See, Javascript hasOwnProperty

Objects in Javascript

Objects in Javascript are a collection of properties and methods or types. Let's take an example for better understanding. Mobile is an object, and its properties include calling, video recording, storage, gaming and many more. In the same way, objects can also have different kinds of properties. If you want to learn more about the objects, then you can refer to the Objects in JS blog.

As we are now familiar with the objects in JS (Javascript), let's talk about the primitives in JS.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Primitives in Javascript

On the other hand, the primitive data type is fully opposite to the objects in JS. The primitive does not have any kind of properties or methods to define them. In Javascript, there are mainly five primitive data types that are as follows:

  • Number
  • String
  • Boolean
  • Null
  • Undefined
     

Up to now, we have covered all our basic concepts related to the blog. It's time to move on to the main topic, which is Object to Primitive Conversion.

Conversion Rules

There are a few rules to convert any object into a primitive. Let's start from there.

Rule 1: There is no conversion from object to boolean. Hence, all objects are considered true in a boolean. There are only strings and numeric conversions.

Rule 2The numeric conversion takes place when subtracting objects or applying mathematical functions.

Rule 3String conversion happens when we output an object like alert(obj) and in contexts like that.

Object to Number Conversion

To convert an object to a number, we will use the Symbol.toPrimitive. This is a symbol that specifies a function-valued property called to convert an object to a corresponding primitive value.

Syntax of Symbol.toPrimitive is as follows:

[Symbol.toPrimitive](hint);

 

Here Symbol is the object whose primitive value is to be found. This function accepts a parameter named "hint" and returns the primitive value of the given symbol object.

The hint function helps the Javascript to identify which conversion to apply. We will see different ways to manipulate the hint function in this blog.

Let's take an example that shows the toPrimitive method by passing the hint so the concept will be clearer for you.

const object1 = {
    [Symbol.toPrimitive](hint) {
        if (hint === 'number') {
            return 100;
        }
        return null;
    }
};
console.log("Value:",+object1);
console.log("Type of object before conversion:",typeof(object1));
console.log("Type of object after conversion:",typeof (+object1));

 

Output:

output

Explanation:

Here, first, we created an object named object1 and then passed the hint "number", which instructed the compiler to convert the object into a number type. And we returned the value 100 there. Note that while printing the output, we used a plus (+) sign which is a unary plus in this case.

In the output screen, we first printed the value that we returned after the conversion. We printed the data types in the next two lines, which indicate before and after conversion.

Object to String Conversion

We will use the same method as above. We will use the Symbol.toPrimitive along with the hint to convert the object into a string. 

Let's take an example.

const object1 = {
    [Symbol.toPrimitive](hint) {
        if (hint === 'string') {
            return 'Hey Ninja';
        }
        return true;
    }
};
console.log("Value:", `${object1}`);
console.log("Type of object before conversion:", typeof (object1));
console.log("Type of object after conversion:", typeof (`${object1}`));

 

Output:

output

Explanation:

In this example, we performed the same conversion process as the above. The only difference is the printing line and the value of the hint. 

In the number conversion example, we used a plus sign to print the number, but here we use a "$" sign instead of plus. The reason is  "$" sign helps the Javascript to print the converted string in the console.

toString and valueOf

If we are using Symbol.toPrimitive in the method, then we can use this for all the hints. However, in the absence of toPrimitive method, JavaScript looks for the methods toString and valueOf. 

We can use the toString method if the hint is "string". The toString method returns a string in the form of "[object Object]." For all other hints, we can use the valueOf method. The valueOf method returns the object itself.

Let's take an example for clarity.

var object1 = {
    name: 'Coding Ninjas'
}
console.log(object1.toString())

 

Output:

output

So, as you can see, if we try to use an object as a string, as in the above example, we will get [object Object] by default. Therefore, anytime using an object as a string, you will have [object Object].

Now let's check whether the value returned by the valueOf method is an object or not. We will take a short example to be clear on this.

var object1 = {
    name: "Coding Ninjas"
};
console.log(object1.valueOf() == object1); 

 

Output:

output

Explanation:

As you can see in the output screen, we get the output "True". This confirms that the value returned by the valueOf object is the object itself.

Operator Conversions

Many operators perform type conversions. For instance, multiplication converts operands to numbers. So while performing operations on Objects, the object is first converted to a primitive, and then the desired operations are performed. 

Let's take a look at an example to understand this:

let obj = {
    toString() {
        return "2";
    }
};

console.log(obj * 2); 
console.log(typeof (obj * 2));
console.log(typeof (obj));

 

Output:

output

Explanation:

It is clear after this example that if we use a multiply operator, then the data type will change to a number, as shown in the second line. On the other hand, if we do not use the operator, the data type will remain the same, i.e., object, as shown in the third line of output.

The same thing will happen if we use other operators in place of multiply.

Let's look at some FAQs now.
 

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

What is an Object in JS?

An object is an entity with a set of properties (primitive values and objects) and behaviours (methods). 

Is an object a primitive data type?

No, an object is a non-primitive data type.

Why does JavaScript store almost everything in objects?

In JS, an object is just a hashmap with key-value pairs. A key is always a string or a symbol, while a value can be anything from strings to integers to booleans to functions to other objects.

What is the Prototype in JS?

Prototypes are the technique by which JavaScript objects inherit features from one another. They are flexible and robust feature that allows you to reuse code and combine objects.

How do you check if it is a number in JavaScript?

You can use the JavaScript typeOf method. If the variable passed is a number, it will return a string named number. 

Conclusion

This article discusses the topic of the Object to Primitive Conversion. In detail, we have seen the definition of objects and primitives. We also discussed conversion rules and how to convert the object to a number and a string.

We hope this blog has helped you enhance your knowledge of the Object to Primitive Conversion. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Optional chaining
Next article
Flags and Descriptors
Live masterclass