Table of Contents
TypeError: .toLowerCase is not a function
occurs when we call toLowerCase()
function on object which is not an string. toLowerCase()
function can be only called on string. To resolve this issue, convert value to string using toString()
,method before calling toLowerCase() method.
Let’s see with help of simple example
1 2 3 4 5 6 |
const s = {}; // will throw TypeError: str.toLowerCase is not a function const lowerCaseStr = s.toLowerCase(); |
You will get following error when you execute the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const lowerCaseStr = s.toLowerCase(); ^ TypeError: s.toLowerCase is not a function at Object.<anonymous> (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 </anonymous> |
We got this error because str
is not an string here.
Check type before calling toLowerCase() method
Check if the object on which you are calling
toLowerCase()
is String or not. Useconsole.log()
to print it. It may beundefined
sometimes.
You can check if it is type of string before calling toLowerCase()
to make sure that toLowerCase()
is being called on string only.
1 2 3 4 5 |
var num=123; num=typeof num === 'string' ?num.toLowerCase():''; console.log(num); |
Output:
1 2 3 |
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 toLowerCase()
method, otherwise return empty string.
You can also check if type variable has toLowerCase method or not.
For example:
We can check if toLowerCase method exists in Number
class.
1 2 3 |
"toLowerCase" in Number.prototype; // False |
Call toLowerCase()
on String object only
Call toString() method on object
Convert object to string using toString()
method and it will work fine.
1 2 3 4 5 |
const n= 123; const lowerCaseStr = n.toString().toLowerCase(); console.log(lowerCaseStr) |
Output:
1 2 3 |
123 |
Use String() constructor
To convert a value to String, use String() constructor.
1 2 3 4 5 |
const n= 123; const lowerCaseStr = String(n).toLowerCase(); console.log(lowerCaseStr) |
Output:
1 2 3 |
123 |
Use + operator
You can convert value to String using + operator and call toLowerCase()
on variable.
1 2 3 4 5 |
const n= 123 + ''; const lowerCaseStr =n.toLowerCase(); console.log(lowerCaseStr) |
Output:
1 2 3 |
123 |
Read also: map is not a function in JavaScript.
That’s all about how to resolve TypeError: toLowerCase is not a function in JavaScript
.