Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ENUM pattern naming convention

I am working on a javascript project which requires use of javascript "Enums" meaning Objects like:

var WinnerEnum = {             Player1: 1,             Player2: 2,             Draw: 0     }; 

This is working great for me, however, I have no idea what is the proper way (according to convention) to name the Enum because as far as I know only class names start with a capital letter (indicating the ability to call a constructor on).

JSHint also outputs the following warning:

Missing 'new' prefix when invoking a constructor. 

If there is no convention, I would appreciate a good way to name enums that would not confuse them with class names. Update 2014 : JSHint no longer does this.

like image 879
Benjamin Gruenbaum Avatar asked Nov 05 '12 13:11

Benjamin Gruenbaum


People also ask

How should enums be named?

Enums are types, so they should be named using UpperCamelCase like classes. The enum values are constants, so they should be named using lowerCamelCase like constants, or ALL_CAPS if your code uses that legacy naming style.

Should enum be capitalized JS?

That is indeed the correct way to name the enum, but the enum values should be ALL_CAPS instead of UpperCamelCase, like this: var WinnerEnum = { PLAYER_1: 1, PLAYER_2: 2, DRAW: 0 }; This is similar to Java's naming convention for enums.

Are enum names plural or singular?

Enums in Java (and probably enums in general) should be singular.

Should enum be uppercase TypeScript?

Conventionally, the enum name and constant names are in Pascal case, where the first letter of each compound word is capitalized.


1 Answers

That is indeed the correct way to name the enum, but the enum values should be ALL_CAPS instead of UpperCamelCase, like this:

var WinnerEnum = {     PLAYER_1: 1,     PLAYER_2: 2,     DRAW: 0 }; 

This is similar to Java's naming convention for enums.

Some references:

  • Google JavaScript Style Guide
  • Stijn de Witt's Blog
  • Enumify documentation

As with coding style in general, you'll find people doing things in many different ways, with each way having its own set of good reason. To make things easiest for anyone reading and working with your code, however, I would recommend using the style which has the most authoritative reference and therefore usually the most widespread adoption.

I couldn't find any reference more authoritative than Google's style guide and the writings above, written by people who have given some serious thought to enums, but I'd be interested to hear of any better references.

like image 55
dharcourt Avatar answered Sep 18 '22 23:09

dharcourt