óCoffeeScript Cookbook

Lowercasing a String


You want to lowercase a string.


Use JavaScript’s String toLowerCase() method:

"ONE TWO THREE".toLowerCase()
# => 'one two three'


toLowerCase() is a standard JavaScript method. Don’t forget the parentheses.

Syntax Sugar

You can add some Ruby-like syntax sugar with the following shortcut:

String::downcase = -> @toLowerCase()
"ONE TWO THREE".downcase()
# => 'one two three'

The snippet above demonstrates a few features of CoffeeScript:

  • The double-colon :: is shorthand for saying .prototype.
  • The “at” sign @ is shorthand for saying this.

The code above compiles in to the following JavaScript:

String.prototype.downcase = function() {
  return this.toLowerCase();
"ONE TWO THREE".downcase();

Note: Although it’s quite common in languages like Ruby, extending native objects is often considered bad practice in JavaScript (see: Maintainable JavaScript: Don’t modify objects you don’t own; Extending built-in native objects. Evil or not?).