24

I have always wondered when to use identifiers (for example, functions) with capital first letter instead of camel case. I always write my JS in camel case like this:

function doStuff() {}

var simpleVar = 'some stuff',
    myAry = [],
    myObj = {};

... But I know I am supposed to name some things with capital first letters. I just don't know WHEN this rule applies. Hope somebody can make things a bit clearer to me.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
patad
  • 9,364
  • 11
  • 38
  • 44

3 Answers3

34

According to the book "Javascript: the good parts", you should only capitalise the first character of the name of a function when you need to construct the object by "new" keyword.

This is called "the Constructor Invocation Pattern", a way to inherits.

louis.luo
  • 2,921
  • 4
  • 28
  • 46
19

The convention is to name constructor functions (i.e. functions that will be used with the new keyword) with starting capital.

function MyType(simpleVar) {
    this.simpleVar = simpleVar;
}

myObject = new MyType(42);
  • 1
    What about variables that happen to start with a capital letter, because they refer to an acronym - should the first letter, or the entire acronym be lowercased? Example: `ECBhandle` vs. `ecbHandle` (it does _not_ matter what ECB means). – Dan Dascalescu Dec 04 '13 at 12:39
  • 2
    @DanDascalescu: Personally, I treat acronyms the same as regular words, so in this case I would opt for `ecbHandle`. Other examples would be `parseXml` or `isbn`. This applies to constructor functions as well: e.g. `XmlParser`. – Peter-Paul van Gemerden Dec 05 '13 at 14:06
  • I like constants to be marked as ALLCAPS. Seems to work. – akauppi Mar 26 '15 at 14:11
6

The name convention states that class names are named with a first capital letter, I'm not sure how it's like with javascript, which is a prototype based language, but basically it's

class ClassName
var varName
function funcName()
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308