Naming variables has always been a source of debates around developers. The general idea is that you should pick a name as short as possible, but long enough to provide meaning, one which would be self-explanatory, for which you needn’t browse the code to understand what it’s used for.
Studying naming conventions can help. Also, having some specially set within your team is a good idea. Here are some that are quite general:
- For variables, you should
use nouns
. Other ideas:- with a plural form for arrays;
- if your variable is a boolean, you should prefix it with
is
,has
,can
;
- For functions, you should
use verbs
, with a recommended format ofactionResource
(e.g.resetPassword
); - Avoid using
my
in the names you pick (e.g.myClearFunctionName
) and other keywords likeif
,else
,for
,switch
,float
,long
etc.; - Do not combine case styles (e.g. use
kebab-case
withsnake_case
orcamelCase
); - Go from general to specific – e.g.
nameFirst
andnameSecond
(name
is the general part,First
andLast
are the specific parts); - Constants should be written in
UPPERCASE
.
Apart from these rather general rules, I found it easier and productive to keep my variables on the positive side (e.g. use isValid
instead of isNotValid
or isInvalid
) throughout the code of a project.
It is hard to apply all of them right from the beginning, but with time and practice, everybody gets better and better.
A source for more best practices is Java
. It is one of the mature programming languages which has solved in its features and rules many of the problems which a novice might encounter while “navigating the rivers” of the flexible javascript.
More information and sources:
- https://en.wikipedia.org/wiki/Naming_convention_(programming)
- https://en.wikipedia.org/wiki/Coding_conventions
- https://hackernoon.com/the-art-of-naming-variables-52f44de00aad
- https://www.dummies.com/web-design-development/javascript/naming-javascript-variables/
- https://medium.com/better-programming/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841
- https://www.youtube.com/watch?v=StzpmOpELGg