How and why does 'z'['toUpperCase']() in JavaScript work?



In this tutorial, we will learn how and why ‘z’[‘toUpperCase’]() works in JavaScript. From the given format, we can say that it calls the toUpperCase() method for the ‘z’ string. It will work the same as the toUpperCase() method, which we invoke by taking any string as a reference.

Let’s understand the syntax of the ‘z’[‘toUpperCase’]() below.

Syntax

let result = 'z'['toUpperCase'](); // returns 'Z', string in upper case

The above syntax is same as the below.

Example

let string = 'z';
let result = string.toUpperCase();

Why does ‘z’[‘toUpperCase’]() work?

In JavaScript toUpperCase() method is used to convert all characters of the string into the upper case. The toUpperCase() is the method of the string.prototype() class.

Before we move ahead with this tutorial, let’s understand the 2 ways to access the properties of any class using its object.

The first way to access the properties of any class using its object is the dot operator, and users can see the syntax below for that.

let obj = new object();
obj.method();
obj.variable;

Now, users can see the second way to access the class properties using its object.

let obj = new object();
obj[method]();
obj[variable];

In the ‘z’[‘toUpperCase’], we have used the second method to access the string class method. Here, ‘z’ is the string, but when we use it with the second syntax, it converts to the object. ‘toUpperCase’ is the method of the String class, and ‘()’ represents the accessed property is the method, and invoke it by taking the object as a reference.

Let’s understand the above format to call the toUpperCase() method using the example below.

Example

In the example below, we have access to the toUpperCase() method of the String class and apply it to the string object. We have used the different string objects and converted them into the upper case in the example below. Users can see the output for the different values.

<html> <body> <h2> How and why does 'z'['toUpperCase']() in JavaScript work? </h2> <h4> Used <i> 'z'['toUpperCase']() </i> for differnet string object values.</h4> <div id = "Output"> </div> <script> let Output = document.getElementById("Output"); Output.innerHTML += "'z'['toUpperCase']() output is : " + 'Z'['toUpperCase']() + '<br/>'; Output.innerHTML += "'ABCd34'['toUpperCase']() output is : " + 'ABCd34'['toUpperCase']() + '<br/>'; Output.innerHTML += "'@#$Rts'['toUpperCase']() output is : " + '@#$Rts'['toUpperCase']() + '<br/>'; </script> </body> </html>

In this tutorial, we have learned how does ‘z’[‘toUpperCase’]() syntax will work. It works as same as string.toUpperCase() method. In the same way, users can access the other class properties, such as variables and methods.


Advertisements