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

In JavaScript, the syntax 'z'['toUpperCase']() works because strings are objects, and you can access object methods using both dot notation and bracket notation. This alternative syntax calls the toUpperCase() method on the string 'z', converting it to uppercase.

Syntax

'z'['toUpperCase']()  // Returns 'Z'

This is equivalent to the more common dot notation:

'z'.toUpperCase()     // Returns 'Z'

Why Does This Work?

In JavaScript, there are two ways to access object properties and methods:

  • Dot notation: object.property
  • Bracket notation: object['property']

String literals like 'z' are automatically wrapped in String objects when you access their methods. Since toUpperCase is a method of the String prototype, you can access it using either notation.

Examples

<html>
<body>
   <h2>String toUpperCase() Using Bracket Notation</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      
      // Using bracket notation
      output.innerHTML += "'z'['toUpperCase']() = " + 'z'['toUpperCase']() + "<br>";
      output.innerHTML += "'hello'['toUpperCase']() = " + 'hello'['toUpperCase']() + "<br>";
      output.innerHTML += "'ABC123'['toUpperCase']() = " + 'ABC123'['toUpperCase']() + "<br>";
      
      // Comparison with dot notation
      output.innerHTML += "<br>Equivalent dot notation:<br>";
      output.innerHTML += "'z'.toUpperCase() = " + 'z'.toUpperCase() + "<br>";
   </script>
</body>
</html>
'z'['toUpperCase']() = Z
'hello'['toUpperCase']() = HELLO
'ABC123'['toUpperCase']() = ABC123

Equivalent dot notation:
'z'.toUpperCase() = Z

Key Points

  • Both 'z'['toUpperCase']() and 'z'.toUpperCase() produce identical results
  • Bracket notation is useful when the method name is stored in a variable
  • String literals are automatically converted to String objects when accessing methods
  • This works with all String prototype methods, not just toUpperCase()

When to Use Each Notation

Use dot notation for normal cases and bracket notation when the property name is dynamic:

<html>
<body>
   <div id="demo"></div>
   <script>
      let demo = document.getElementById("demo");
      let methodName = "toUpperCase";
      
      // Dynamic method access using bracket notation
      demo.innerHTML = "Dynamic call: " + 'hello'[methodName]();
   </script>
</body>
</html>
Dynamic call: HELLO

Conclusion

The 'z'['toUpperCase']() syntax works because JavaScript allows bracket notation to access object methods. While functionally identical to dot notation, bracket notation is useful for dynamic property access.

Updated on: 2026-03-15T23:18:59+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements