JavaScript toLowerCase()
Summary: in this tutorial, you’ll learn how to use the JavaScript String.prototype.toLowerCase()
method to return a string with all the characters converted to lowercase.
Introduction to the JavaScript toLowerCase() method
The toLowerCase()
method returns a new string with all characters converted to lowercase. The following shows the syntax of the toLowerCase()
method:
str.toLowerCase()
Code language: CSS (css)
For example:
const message = 'Hi';
const newMessage = message.toLowerCase();console.log(newMessage);
Code language: JavaScript (javascript)
Output:
hi
Because a string is immutable, the toLowerCase()
method doesn’t change the original string. Instead, it returns a new string with all characters converted to lowercase.
Calling JavaScript toLowerCase() method on null or undefined
If you call the toLowerCase()
method on null
or undefined
, the method will throw a TypeError
exception.
The following findUserById
function returns a string if the id
is greater than zero or null
otherwise:
const findUserById = (id) => {
if (id > 0) {
// look up the user from the database
// ...
//
return 'admin';
}
return null;
};
Code language: JavaScript (javascript)
If you call the toLowerCase()
method on the result of the findUserById()
function, you’ll get the TypeError
when the id is zero or negative:
console.log(findUserById(-1).toLowerCase());
Code language: CSS (css)
Error:
TypeError: Cannot read properties of null (reading 'toLowerCase')
Code language: JavaScript (javascript)
To make it safe, you can use the optional chaining operator ?.
as follows:
console.log(findUserById(-1)?.toLowerCase());
Code language: CSS (css)
Output:
undefined
Code language: JavaScript (javascript)
Converting a non-string to a string
The toLowerCase()
method will convert a non-string value to a string if you set its this
value to a non-string value. For example:
const user = {
username: 'JOE',
toString() {
return this.username;
},
};const username = String.prototype.toLowerCase.call(user);
console.log(username);
Code language: JavaScript (javascript)
Output:
joe
In this example, we invoke the toLowerCase()
method with the this
sets to the user
object by using the call()
method. The toLowerCase()
method converts the user
object to a string by calling its toString()
method.
Summary
- Use the
toLowerCase()
method to return a string with all characters converted to lowercase.