Writing Meaningful Variables and Why It Matters

This article is a complementary resource to the Learn JavaScript Basics course.

Writing Meaningful Variables and Why It Matters

Variable names are more than just labels for storing data—they're the building blocks of readable and maintainable code. For example:

let temp = 5;

Here, temp could represent anything—temperature, a temporary value, or something else.

While you might be confident about a variable name when you're writing the code, it can become confusing when someone else reads it (or when you read it after a few weeks).

Let's explore why it's so important to use proper variable names and how you can do so.


What Makes a Variable Good?

Good variable names enhance code readability, simplify maintenance, and reduce potential confusion.

When names are descriptive, they instantly convey what the variable represents, making it easier for others to understand and modify the code.

Good Examples:

let itemPrice = 50;
let taxRate = 0.07;
let totalPrice = itemPrice + (itemPrice * taxRate);

Bad Examples:

let x = 50;
let y = 0.07;
let z = x + (x * y);

It's unclear what x, y, or z represent. Clear names reduce confusion, especially as your project grows.


Practical Tips for Naming Variables

Be Descriptive

Use names that describe what the variable holds (e.g., studentName, purchaseAmount).

Be Concise

While being descriptive is important, you should also try to keep variable names concise. Avoid excessively long names.

// Good
let studentName;

// Bad
let studentFullNameForRegistrationPurposes;

Avoid Abbreviations

Using abbreviations can make variable names harder to understand. For example:

// Good
let firstName = "John";
let count = 5;

// Bad
let fn = "John";
let cnt = 5;

Avoid Reserved Words

Don't use JavaScript's reserved keywords like console, let, or const as variable names.

Note: You might not know all reserved words yet, but make sure to avoid the ones you are aware of.


Naming Conventions

Naming conventions help maintain consistency and readability in your code. Choose a naming convention and stick with it:

  • Camel Case: Words are concatenated without spaces, with the first letter of each subsequent word capitalized (e.g., userName, totalPrice, isValid).
  • Pascal Case: Similar to the camel case, but with the first letter of the first word also capitalized (e.g., UserName, TotalPrice, IsValid).
  • Snake Case: Lowercase words separated by underscores (e.g., user_name, total_price, is_valid).

Choose a convention that fits your language or team standards, and stick with it consistently.


Takeaway

Choosing meaningful variable names is essential for making your code:

  • Readable
  • Maintainable
  • Easier to debug

Clarity in naming is a small effort that pays off in the long run, making your code more understandable for you and others.