TypeError: toUpperCase is not a function in JavaScript

TypeError: .toUpperCase is not a function occurs when we call toUpperCase() function on object which is not an string. toUpperCase() function can be only called on string. To resolve this issue, convert value to string using toString() ,method before calling toUpperCase() method.

Let’s see with help of simple example

const s = {};

//  will throw TypeError: str.toUpperCase is not a function
const upperCaseStr = s.toUpperCase();

You will get following error when you execute the program:

const upperCaseStr = s.toUpperCase();
                       ^

TypeError: s.toUpperCase is not a function
    at Object. (HelloWorld.js:4:24)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

We got this error because str is not an string here.

Convert object to string using toString() method and it will work fine.

const n= 123

const lowerCaseStr = n.toString().toUpperCase();

Output:

123

You can also assert if it is type of string before calling toUpperCase() to make sure that toUpperCase() is being called on string only.

var num=123;
num=typeof num === 'string' ?num.toUpperCase():'';
console.log(num);

Output:


As you can see num is not a string, so result is empty string.

We used ternary operator to check if num is string or not. If it is a string, call the toUpperCase() method, otherwise return empty string.

Read also: map is not a function in JavaScript.

That’s all about how to resolve TypeError: toUpperCase is not a function in JavaScript.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.