I've been a JavaScript developer for about three years now, and while I can comfortably write scalable and maintainable code without relying on AI, I've hit a wall when it comes to naming my variables. I often find myself staring at the screen, stuck on how to name them.
A recent example is when I had two similar variables. For instance, when users select multiple images in the UI, I created an array of selected image IDs and named it `selectedImageIds`. Later, for a feature where users can click an info button to view detailed information about one of those images, I named that variable `SelectedImageId`. The only difference is an 's' at the end, and it's been pointed out to me that I could use something like `activeImageId` for better clarity.
So I'm curious, how do all of you handle naming your variables? What strategies do you use to ensure they clearly convey their purpose?
2 Answers
I totally get the struggle! One thing that helps me is thinking about the context of the variable's use case. Instead of just `selectedImageId` and `selectedImageIds`, you could use names like `currentImageId` for the single selection, and `selectedImageIds` for the array to clarify their roles. That way, it's easy to understand at a glance what each variable represents without getting hung up on tiny differences. Also, I keep a consistent naming convention across projects which makes it easier when I switch between them.
When I name my variables, I often try to think in terms of actions or states. For example, if a variable is meant to store a list of things that are currently selected, I might name it `currentlySelectedImages`. This way, the variable name conveys not just what it holds, but also its relevance to the application state. It’s all about creating clarity not just for yourself, but for anyone else who might read your code later.
That makes a lot of sense! It’s definitely more informative than just using basic descriptors. I'll start trying to incorporate that into my naming.
That's a smart approach! I've found that adding a prefix can also help. For instance, if you're dealing with an array of images, you could use `imageSelection` for the array and `imageDetail` for the single image context. It really clarifies the difference.