Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for const object keys in ES6

Is there a recommended naming convention for key names within a const object in es6? I haven't been able to find a resource which states if they should be uppercase or lowercase.

const COLOR_CODES = {   BLUE: 1,   RED: 1 }; 

vs

const COLOR_CODES = {   blue: 1,   red: 1 }; 

The examples from this MDN article show both styles, so maybe both are acceptable.

like image 510
mralexlau Avatar asked Oct 27 '16 18:10

mralexlau


People also ask

How do you name a const?

If a constant is described by more than one word, you can use the underscore character ( _ ) between the words. For example, the constant name COMPUTER NAME is wrong. Instead, you might use COMPUTER_NAME , or even COMPUTERNAME . A valid constant name can start with a letter or an underscore.

What does const {} mean in JavaScript?

In JavaScript, `const` means that the identifier can't be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable.

What is constant naming convention?

Constants. Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.


2 Answers

NOTE: be aware that the accepted response has a link to an obsolete Google style guide

This is nice (string literals or integer literals):

const PI = 3.14; const ADDRESS = '10.0.0.1'; 

but...

const myObject = { key: 'value' }; const userSuppliedNumber = getInputNumber() 

Google JavaScript Style Guide says:

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used.

Every constant is a @const static property or a module-local const declaration, but not all @const static properties and module-local consts are constants. Before choosing constant case, consider whether the field really feels like a deeply immutable constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough.

JavaScript.info says:

...capital-named constants are only used as aliases for “hard-coded” values.

like image 73
SandroMarques Avatar answered Oct 04 '22 10:10

SandroMarques


According to Google it would be all caps. Speaking from experience, most of the other programming languages have all caps so I would suggest using that.

Use NAMES_LIKE_THIS for constant values.

Use @const to indicate a constant (non-overwritable) pointer (a variable or property).

Google javascript guide https://google.github.io/styleguide/javascriptguide.xml

like image 23
Murf Avatar answered Oct 04 '22 10:10

Murf