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.
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
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.
JavasScript.info says:
...capital-named constants are only used as aliases for “hard-coded” values.
Google once recommended the following:
const COLOR_CODES = {
BLUE: 1,
RED: 1
};
See: https://google.github.io/styleguide/javascriptguide.xml#Constants
- Use
NAMES_LIKE_THIS
for constant values. - Use
@const
to indicate a constant (non-overwritable) pointer (a variable or property). - Never use the
const
keyword as it's not supported in Internet Explorer.
However, the updated style guidelines have different recommendations.
Naming conventions are all over the place, I personally still haven't decided on my preference but to add to the discussion this is what Airbnb JavaScript Style Guide says (see the last examples):
// bad
const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';
// bad
export const THING_TO_BE_CHANGED = 'should obviously not be uppercased';
// bad
export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';
// ---
// allowed but does not supply semantic value
export const apiKey = 'SOMEKEY';
// better in most cases
export const API_KEY = 'SOMEKEY';
// ---
// bad - unnecessarily uppercases key while adding no semantic value
export const MAPPING = {
KEY: 'value'
};
// good
export const MAPPING = {
key: 'value'
};
来源:https://stackoverflow.com/questions/40291766/naming-convention-for-const-object-keys-in-es6