TypeError: Cannot convert object to primitive value in JavaScript
TypeError: Cannot convert object to primitive valueShort answer
JavaScript turns an object into a string or number by calling Symbol.toPrimitive, then valueOf and toString. The TypeError appears when none of them returns a primitive: an object created with a null prototype has no toString, and a custom conversion method that returns an object is rejected.
Fix it fast
1Find out which cause you have
Find the object being converted: the value in the template literal, string concatenation, or comparison on the line of the stack trace. Check whether it has a prototype.
console.log(Object.getPrototypeOf(value), typeof value?.toString);2Match what you see, then jump to its fix
- 1
The value comes from Object.create(null), a parser, or a library that returns prototype-less lookup objects; getPrototypeOf prints nullThe object has a null prototypeFix - 2
The object defines [Symbol.toPrimitive], toString or valueOf, and the error appears only when it is convertedA conversion method returns an objectFix
- 1
What does the error look like?
TypeError: Cannot convert object to primitive value
Cause 1 of 2
The object has a null prototype
1Check
Objects that inherit from Object.prototype get toString. Null-prototype objects do not, so implicit conversion has nothing to call.
const o = Object.create(null);
console.log(typeof o.toString);2Fix
Do not convert the object directly. Print its contents with JSON.stringify, call Object.prototype.toString on it explicitly, or give it a conversion method.
console.log(JSON.stringify(o));
console.log(Object.prototype.toString.call(o)); // [object Object]
o[Symbol.toPrimitive] = () => 'custom';3Verify
The template literal no longer throws.
console.log(`${o}`);Confirmed by developer.mozilla.org
Cause 2 of 2
A conversion method returns an object
1Check
[Symbol.toPrimitive]() must return a primitive, or a TypeError is thrown. With toString and valueOf, the error appears when no related method returns a primitive.
const bad = { [Symbol.toPrimitive]: () => ({}) };
try { +bad } catch (e) { console.log(e.name) }2Fix
Return a string, number or boolean from the conversion method, using the hint when the result depends on it.
const good = {
[Symbol.toPrimitive](hint) {
return hint === 'number' ? 10 : 'hello';
},
};3Verify
Convert it with a template literal and with unary plus.
console.log(`${good}`, +good);Confirmed by developer.mozilla.org
How do I stop it coming back?
- Avoid Object.create(null) for data you will log or interpolate, or convert it explicitly with JSON.stringify.
- Make any custom toString, valueOf or Symbol.toPrimitive return a primitive.
- Log objects with console.log(obj) and not by string concatenation.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
Related fixes
Back end
The AWS SDK in Node.js cannot find any credentials
Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
The AWS SDK walks a fixed credential chain: code, environment variables, the shared files in ~/.aws, then role sources such as ECS or EC2.
3 causes, each with a fixBack end
AWS SDK for JavaScript v3 cannot find credentials, even for DynamoDB Local
A DynamoDB client pointed at http://localhost:8000 fails with the same message
The SDK walked its default credential provider chain and found nothing.
3 causes, each with a fixBack end
AWS SDK says the security token included in the request is invalid
The security token included in the request is invalid
The call reached AWS but the credentials it carried were refused.
3 causes, each with a fixBack end
Amazon Cognito says the user pool client does not exist
ResourceNotFoundException (HTTP status code 400) returned by InitiateAuth
Cognito looks the app client ID up inside the Region you call.
3 causes, each with a fixBack end
TypeError when building a Map or object from a mapped or filtered array
TypeError: Iterator value undefined is not an entry object
new Map() and Object.fromEntries() expect every item to be a [key, value] pair.
3 causes, each with a fixBack end
Browser does not reload when I save a Blade file under Vite
CSS and JavaScript hot update, but view changes need a manual refresh
Vite only reloads the page for Blade files when the Laravel plugin's refresh option is on.
3 causes, each with a fix