Good naming convention in JS?
I don't write much JS soo this problem only come up recently. My first idea is to have all of my function a "verb" like
getAllItems or closeTabById. then for variable I would use "noun" like itemCount . Are there any recommended rule for this?12 Replies
Nope, you can write whatever makes sense to you. Those examples are pretty good and easy to grasp.
I usually use
getSomething when I need to retrieve data, either from some other function or a network request and setSomething for updating a value somewhere. Actions should be clear don't be afraid of writing long function names... not that I would encourage you to do that, but better have a long name than a cryptic abbreviation.It did get confusing sometimes because I got a function called
countItem() and then I got a variable called itemCount=0Depends on the context. If
items is an array you can have no variable at all and compute it with items.length as needed.
You can name it something like getItemCount.oh I see
adding a
get does make it clearerIn general, if you have a lone variable called
somethingCount or somethingItems that may be a good indicator to use a more object-oriented approach. The simple fact of interacting with a class instance will make things much more obvious, for example:
+1 for the private property 👍
Updated to show a use case later on, although the names of this example, ironically, are terrible
If you are using this for a shopping cart then you would do something like
cart.itemCount. Or if you are working with search results, this could be a query.itemCount or something like that. The idea is that there's a clear association between the data you want with a particular object which gives a concise hint as to what to expect from it (and easy to search in the source code).tbh I have never touched
class in JS lol
I just export all of my function and use it when I need themYou don't really need them it's just a way of organizing your code in logical units. If you find that you're having trouble keeping track of your functions/variables however, this may be a good excuse to look into it.
You don't have to change all your code to classes anyway, so start small and see if it helps.
thanks for the help ♥️
Don't forget to use
is, has, can, etc prefix for booleans!
isActive, canCheckout, hasCompletedOnboarding, things like that.Classes and helper functions have 2 very different use cases. Classes are for stateful logic while helper functions are mostly stateless.
If you have a class without a state (public or private props) you should not be using a class. (And don't group up helper functions in an object, doing so prevents the unused functions from being tree shaked by the build tool)