Javascript Method Naming lowercase vs uppercase

30,656

Solution 1

A popular convention in Javascript is to only capitalize constructors (also often mistakenly called "classes").

function Person(name) {
  this.name = name;
}
var person = new Person('John');

This convention is so popular that Crockford even included it in its JSLint under an optional — "Require Initial Caps for constructors" : )

Anything that's not a constructor usually starts with lowercase and is camelCased. This style is somewhat native to Javascript; ECMAScript, for example (ECMA-262, 3rd and 5th editions) — which JavaScript and other implementations conform to — follows exactly this convention, naming built-in methods in camelcase — Date.prototype.getFullYear, Object.prototype.hasOwnProperty, String.prototype.charCodeAt, etc.

Solution 2

It honestly depends. Your first method is called Camel Coding, and is a standard used by Java and C++ languages, and taught a lot in CS.

The second is used by .NET for their classes and then the _camelCode notation used for private members.

I like the second, but that's my taste, which is what I think this depends on.

Share:
30,656
jonen
Author by

jonen

Updated on March 29, 2020

Comments

  • jonen
    jonen about 4 years

    I am for the most part a developer in ASP.NET and C#. I name my variables starting in lowercase and my methods starting in uppercase. but most javascript examples I study have functions starting in lowercase. Why is this and does it matter?

    function someMethod() { alert('foo'); }
    

    vs

    function SomeMethod() { alert('bar'); }
    
  • the12
    the12 about 7 years
    Just wondering... if you were to name constructors starting with a lower case letter, and non-constructor functions starting with an upper case letter, would the resulting code still output anything, or would you get an error?
  • Pete - iCalculator
    Pete - iCalculator about 7 years
    Simple and accurate, I think this is the better answer. Voted up for noting that the approach taken is academic, the code processes regardless of the user preference in structure.
  • David Moores
    David Moores about 7 years
    @the12 As long as you reference the constructors and functions with the same casing it will all be fine. Naming conventions are purely recommendations on how you should write your code. It means that if you're writing code that other people may read over, it is easier for them to follow.
  • Nillus
    Nillus about 4 years
    Yet there are no classes at all in Javascript. The latest keyword class in ES2015 is primarily sintactical sugar, as stated here.
  • Nillus
    Nillus almost 4 years
    No, they don't. Classes are not part of Javascript, what you see declared as "class" is just "emulated" to let people used to class OOP paradigm work client-side without having to learn javascript prototype-based OOP implementation. JS classes simply do not exist.