javascript

Variable Naming Rules

Learn the essential JavaScript variable naming rules: valid characters, case sensitivity, reserved keywords, and best practices for clear, readable code.

9 min read 8 sections Tutorial
Share

Every variable in JavaScript needs a name. These names are not just random words; they must follow specific rules. Understanding these rules helps you write code that JavaScript can understand and other people can read. This tutorial will teach you all about naming variables correctly. You will learn what names are allowed, what names are forbidden, and how to choose good names that make your code easy to understand.

JavaScript Variable Naming Rules

JavaScript Variable Naming Rules

When you create a variable, you give it a unique name. This name is how you find and use the value stored inside that variable later. JavaScript has strict rules for what makes a valid name.

These rules are important because they prevent errors and make sure your code runs correctly. Following best practices also helps other programmers understand your code faster.

What are Naming Rules?

Variable naming rules are a set of guidelines that dictate what characters can be used in a variable name and how they must be arranged for JavaScript to recognize them.

Valid Characters

Variable names can only use letters, numbers, underscores (_), and dollar signs ($).

Starting Character

Names must start with a letter, an underscore (_), or a dollar sign ($).

Reserved Keywords

You cannot use JavaScript's special words (like if, for, let) as variable names.

Case Sensitive

JavaScript treats myVar and myvar as two completely different variables.

Basic Naming Rules

Getting Started

Basic Naming Rules

The most important rules for variable names are simple. They tell you what characters you can use and where they can go. Think of it like a secret code that JavaScript understands.

First, a variable name must start with a letter (like 'a' through 'z'), an underscore (_), or a dollar sign ($). It cannot start with a number. Second, after the first character, you can use letters, numbers, underscores, or dollar signs.

javascript
1// --- Valid variable names ---
2let userName = "Alice"; // Starts with a letter
3let _score = 100; // Starts with an underscore
4let $price = 29.99; // Starts with a dollar sign
5let gameLevel1 = 5; // Contains numbers, but starts with a letter
6
7// --- Invalid variable names (will cause errors) ---
8// let 1stPlayer = "Bob"; // ❌ Error: Cannot start with a number
9// let user-name = "Charlie"; // ❌ Error: Hyphens are not allowed (JavaScript thinks it's subtraction)
10// let total price = 50; // ❌ Error: Spaces are not allowed
11
12console.log(userName); // Alice
13console.log(_score); // 100
14console.log($price); // 29.99
15console.log(gameLevel1); // 5

Avoid starting with a number

A very common mistake for beginners is trying to start a variable name with a number. This will always cause a syntax error in JavaScript. Remember: letters, _, or $ only for the first character.

Case Sensitivity and Reserved Words

Case Sensitivity and Reserved Words

JavaScript is a 'case-sensitive' language. This means that uppercase letters and lowercase letters are treated as different characters. So, myVariable and myvariable are not the same thing.

Also, JavaScript has special words called 'reserved keywords'. These words already have a meaning in JavaScript (like if, for, function, let, const). You cannot use these words as your own variable names because JavaScript would get confused.

javascript
1let score = 10; // 'score' with lowercase 's'
2let Score = 20; // 'Score' with uppercase 'S' is a different variable
3let SCORE = 30; // 'SCORE' all caps is yet another different variable
4
5console.log(score); // 10
6console.log(Score); // 20
7console.log(SCORE); // 30
8
9// --- Trying to use a reserved keyword as a variable name ---
10// let if = true; // ❌ Error: 'if' is a reserved keyword
11// let const = 50; // ❌ Error: 'const' is a reserved keyword
12// let function = () => {}; // ❌ Error: 'function' is a reserved keyword
13
14// You can use keywords as part of a name, just not the whole name
15let ifCondition = true; // ✅ Valid
16console.log(ifCondition); // true
✗ BadWrong — using reserved keyword
let for = 10; // ❌ SyntaxError: 'for' is a reserved keyword
console.log(for);
✓ GoodCorrect — using a valid name
let count = 10; // ✅ 'count' is a valid variable name
console.log(count); // 10
let forLoopCounter = 0; // ✅ 'forLoopCounter' is valid
console.log(forLoopCounter);

Naming Conventions: Making Names Readable

Naming Conventions: Making Names Readable

While JavaScript has rules for what names are valid, there are also common practices for how to write names that are easy for humans to read. These are called 'naming conventions'.

The most popular convention in JavaScript is 'camelCase'. This means the first word starts with a lowercase letter, and every next word starts with an uppercase letter, with no spaces in between. For example, userName or totalScore.

camelCase (Variables/Functions)
// Preferred for variables and functions
let userName = "Alice";
let totalScore = 500;
function calculatePrice() {
// ...
}
// Always start with lowercase
VS
PascalCase (Classes)
// Preferred for Class names
class UserProfile {
// ...
}
class ProductItem {
// ...
}
// Always start with uppercase

Stick to camelCase for variables and functions

For almost all your variables and functions in JavaScript, you should use camelCase. It's the most common and expected style. This makes your code consistent with other JavaScript code you'll see.

Writing Clear and Descriptive Names

Writing Clear and Descriptive Names

Beyond just following the rules, good variable names are descriptive. They tell you what the variable holds without needing to read comments or guess. Clear names make your code much easier to understand and fix later.

Imagine reading a story where all the characters are named 'A', 'B', 'C'. It would be confusing! Good variable names are like good character names – they help you follow the story of your code.

1

Be descriptive, not vague

Choose names that clearly explain the variable's purpose. userAge is better than age, and totalPrice is better than amount.

javascript
1let userAge = 30;
2let totalPrice = 150.75;
2

Avoid single-letter names (mostly)

While x or i are sometimes okay for simple loop counters, avoid them for important data. index or counter are often clearer.

javascript
1for (let i = 0; i < 10; i++) { /* ... */ }
2let firstName = "Jane";
3

Use consistent prefixes for booleans

For variables that hold true or false values (booleans), start their names with is, has, or can to show their type. Example: isLoggedIn, hasPermission, canEdit.

javascript
1let isLoggedIn = true;
2let hasDiscount = false;
4

Keep names reasonably short

Aim for a balance. Names should be descriptive but not overly long. customerName is good, theNameOfTheCurrentCustomer is too long.

javascript
1let customerName = "John Doe";

Vague names cause confusion and bugs

Using names like data, item, or x for important variables makes your code very hard to read and debug. You will forget what data actually means, leading to mistakes. Always strive for clarity!

Quick Reference for Naming

Quick Reference for Naming

Rule/ConventionDescriptionExample (Valid)Example (Invalid)
Starts withLetter, `_`, or `$``userName`, `_id`, `$value``1stPlace`, `~temp`
Allowed charactersLetters, numbers, `_`, `$``myVar1`, `_config_``my-var`, `total amount`
Case SensitiveUppercase/lowercase are different`count` vs `Count`N/A (it's a feature, not an error)
Reserved wordsCannot use keywords`myFunction`, `letVariable``function`, `class`
ConventioncamelCase for variables/functions`firstName`, `calculateTotal``first_name`, `CalculateTotal`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of these is a VALID JavaScript variable name?

Quick Check

What is wrong with trying to use let if = true;?

Quick Check

If you declare let myVar = 5; and let MyVar = 10;, what will console.log(myVar); print?

Quick Check

Which naming convention is generally preferred for variables and functions in JavaScript?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Start with — a letter, underscore (_), or dollar sign ($). Never a number.
  • 2Allowed characters — letters, numbers, _, and $. No spaces or hyphens (-).
  • 3Case-sensitivemyVar is different from MyVar. Pay attention to capitalization.
  • 4Reserved keywords — cannot use words like if, for, let, const as variable names.
  • 5camelCase — use for variables and functions (e.g., userName, calculateTotal).
  • 6PascalCase — use for class names (e.g., UserProfile, ProductItem).
  • 7Be descriptive — choose names that clearly explain what the variable stores.
  • 8Avoid vague namesdata, item, x are usually too generic. Be specific.
  • 9Boolean prefixes — use is, has, can for true/false variables (e.g., isLoggedIn).
  • 10Consistency — stick to one naming style throughout your project for readability.

Data Types

Understand what kinds of values (numbers, text, true/false) variables can hold.

Operators

Learn how to perform calculations and comparisons using your variables.

Variable Scope

Discover where in your code a variable can be accessed and used.

Best Practices

Explore more general tips for writing clean, maintainable JavaScript code.

You've mastered JavaScript Naming Rules!

You now know how to create valid and descriptive variable names in JavaScript. Following these rules and conventions will make your code error-free, easier to read, and simpler for others to understand. This is a crucial skill for every programmer!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning