261

I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.

How do you name your variables, functions, objects and such?

I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.

The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
peirix
  • 36,512
  • 23
  • 96
  • 126
  • An up-to-date guide to common sense Naming Conventions in JS: https://www.robinwieruch.de/javascript-naming-conventions – Robin Wieruch Jan 30 '20 at 10:18

6 Answers6

203

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Geoff
  • 9,340
  • 7
  • 38
  • 48
  • 30
    JSLint can be too radical and restrictive for many developers, then [JSHint](http://www.jshint.com/) can be better choice. – Pavel Hodek Jan 02 '12 at 20:18
  • There is also the [Online Javascript Beautifier][1] (http://jsbeautifier.org) which seems to use all the Douglas Crockford conventions to format the code. It does not address the naming of variables and functions though. [1]: http://jsbeautifier.org – Jean-Philippe Martin May 15 '12 at 15:12
  • 8
    Crockford doesn't go into this level of detail, but 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:37
  • 14
    Although it's a good link, I can't believe a "link answer" has so many votes. You could at least extract & format the relevant parts of the linked page. – Adriano Nov 13 '14 at 09:26
  • 2
    I think he is doing fine with the link. If you are so concerned you should edit the post. – nckbrz Dec 12 '14 at 13:21
  • 4
    I really look up to Crockford but his code conventions seem very outdated. I would advice looking at @PavelHodek answer further down the list – Per Hornshøj-Schierbeck Apr 20 '15 at 09:13
  • This is not an answer. The document linked doesn't talk at all about naming conventions for variables, but for code in general. – João Pimentel Ferreira Nov 23 '18 at 22:41
160

As Geoff says, what Crockford says is good.

The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.

var footer = document.getElementById('footer');

var $footer = $('#footer');

Benjamin R
  • 555
  • 6
  • 25
Deebster
  • 2,829
  • 1
  • 26
  • 26
116

You can follow the Google JavaScript Style Guide.

In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

See a nice collection of JavaScript Style Guides And Beautifiers.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Pavel Hodek
  • 14,319
  • 3
  • 32
  • 37
  • 16
    I'm not sure if I fully agree with that, considering that they developed Dart and GWT (the chrome extensions javascript api is also very java-like). To some teams in Google, the best way to develop javascript might be to write it in some other language. – badunk Sep 10 '12 at 21:30
  • 2
    I always found Google's private naming convention *odd*, instead of `_fooBar` they do `fooBar_` - Microsoft got it right: http://www.asp.net/ajaxlibrary/act_contribute_codingStandards.ashx – Daniel Sokolowski Jan 23 '14 at 04:49
  • 3
    @DanielSokolowski What about when using intellisense? If you prefix a large number of variables with an underscore, then that's just another character you have to type every time you access those variables. With it at the end, your intellisense list looks cleaner and it's just a little bit quicker to find what you need. – FreeAsInBeer Apr 07 '14 at 15:00
  • @FreeAsInBeer true about the extra character but I don't think its faster. Typing `_` when referencing private vars would result in intellisense right away limiting the results; in the end thought it's personal preference. – Daniel Sokolowski Apr 14 '14 at 13:37
  • 1
    Thanks for linking to the list of style guides. I don't know if one is worth following exclusively or how to decide yet which one or whether I should use an amalgamation. But knowing where to find several in one place is a real boon. – Roger_S Dec 09 '14 at 20:18
10

One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,

define(['Lightbox'],function(Lightbox) {
  var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
  myLightbox.show('hello')
})

I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:

define(['theLightbox'],function(theLightbox) {
  theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SimplGy
  • 20,079
  • 15
  • 107
  • 144
6

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.

Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Javier
  • 60,510
  • 8
  • 78
  • 126
2

That's an individual question that could depend on how you're working.

Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").

I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".

In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ivar
  • 4,344
  • 6
  • 38
  • 53
  • 2
    "so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts," This statement is **inaccurate**. You can correctly have "namespaced" functions and objects that do not bleed through multiple javascript frameworks. There was a very good presentation on how to achieve this from MIX11 http://channel9.msdn.com/Events/MIX/MIX11/OPN08 – Chris Marisic Apr 25 '11 at 14:19
  • Re *"put the variable type at the beginning of the variable"*: That It is ***system*** Hungarian notation, not the real Hungarian notation. The Windows documentation team [messed it up](https://twit.tv/shows/triangulation/episodes/277)—at [04 min 00 secs](https://cdn.twit.tv/audio/tri/tri0277/tri0277.mp3) (even though the author explicitly warned against it). And now it is tainted. – Peter Mortensen Oct 12 '22 at 20:15