I am learning Javascript. I am trying to convert Object. While trying to convert it's only printing Number not string. while printing string it shows complete object not string. Below is my code.
let user2 = {
name: "Akash",
surName: "Jangra",
age: 30,
Salary: 25000,
[Symbol.toPrimitive](hint) {
console.log(`hint : ${hint}`);
return hint == "string" ? `{name: "${this.name}"}, ${this.surName}` : this.Salary;
}
};
console.log(user2);
console.log(+user2);
console.log(user2 + 500);
2 Answers 2
Try
console.log(`${user2}`);
When you do
console.log('' + user2);
Hint equals default
You have to 'tell' JavaScript what to convert to explicitly. Examples:
var x = { test: 1 };
// Console log the object
console.log(x);
// Try to convert to number
console.log(0 + x);
// Try to convert to string
console.log(`${x}`);
// I thought this would work as wel, but is does not convert to 'string' but to 'default'
console.log('' + x);
// Try to bool
console.log(!!x);
Edit: Like ezotos said. This is really uncommon to do in javascript though.
Comments
This is actually a very uncommon practice. Object in JavaScript are usually keep primitive. Thus, only containing data.
I would suggest to create a function that takes your source object as an argument and returns the desired output.
If you need the functionality in such an object, think about using a class instead.
And overload the toString() method for example.