JavaScript toUpperCase()

Summary: in this tutorial, you’ll learn how to use the JavaScript String.prototype.toUpperCase() method to return a string with all the characters converted to uppercase.

Introduction to the JavaScript toUpperCase() method

The toUpperCase() method returns a new string with all characters converted to uppercase. Here’s the syntax of the toUpperCase() method:

str.toUpperCase()Code language: CSS (css)

For example:

const message = 'Hello';
const newMessage = message.toUpperCase();

console.log(newMessage);Code language: JavaScript (javascript)

Output:

HELLO

It’s important to notice that a string is immutable. Therefore, the toUpperCase() method doesn’t change the original string. Instead, it returns a new string with all characters converted to uppercase.

Calling toUpperCase method on undefined or null

If you call the toUpperCase() method on null or undefined, the method will throw a TypeError exception. For example, the following getUserRanking() function returns a string if the id is greater than zero or undefined otherwise:

const getUserRanking = (id) => {
  if (id > 0) {
    return 'Standard';
  }
};Code language: JavaScript (javascript)

Note that a function returns undefined by default when you do not explicitly return a value from it.

If you call the toUpperCase() method on the result of the getUserRanking() function, you’ll get the TypeError when the id is zero or negative:

console.log(getUserRanking(-1).toUpperCase());Code language: CSS (css)

Error:

TypeError: Cannot read properties of undefined (reading 'toUpperCase')Code language: JavaScript (javascript)

To avoid the error, you can use the optional chaining operator ?. like this:

console.log(getUserRanking(-1)?.toUpperCase());Code language: CSS (css)

Output:

undefinedCode language: JavaScript (javascript)

Converting a non-string to a string

The toUpperCase() method will convert a non-string value to a string if you set its this value to a non-string value. For example:

const completed = true;
const result = String.prototype.toUpperCase.call(completed);

console.log(result);Code language: JavaScript (javascript)

Output:

TRUECode language: PHP (php)

In this example, the completed is true, which is a boolean value. When we call the toUpperCase() method on the completed variable and set the this of the toUpperCase() to completed, the method converts the boolean value true to the string 'TRUE'.

Summary

  • Use the toUpperCase() method to return a string with all characters converted to uppercase.
Was this tutorial helpful ?