When you write JavaScript code, you need to store pieces of information. You do this using variables. This tutorial teaches you the best ways to declare variables using `const` and `let`, and why you should avoid `var`. You will learn how to choose the right keyword for different situations to make your code easier to understand and less prone to errors.
Best Practices for Variable Declaration
Best Practices for Variable Declaration
When you write JavaScript code, you need to store pieces of information. You do this using variables. Variables are like labeled boxes where you can keep data. This tutorial teaches you the best ways to declare variables using const and let, and why you should avoid var. You will learn how to choose the right keyword for different situations to make your code easier to understand and less prone to errors.
What are Variable Declaration Best Practices?
Variable declaration best practices are rules and guidelines that help you choose the correct keyword (const, let, or var) and naming conventions for your variables, making your code more predictable and maintainable.
Prefer `const` First
Always try to use const for variables whose values will not change after they are first set.
Use `let` When Needed
Switch to let only if you know the variable's value will be updated later in your code.
Avoid `var`
Stay away from var because it has confusing rules about scope and hoisting that can cause bugs.
Clear Naming
Give your variables clear and descriptive names so anyone reading your code understands their purpose.
Understanding `let`, `const`, and `var`
Understanding `let`, `const`, and `var`
JavaScript gives you three keywords to declare variables: var, let, and const. Each one works a little differently. Understanding these differences is the first step to writing good code. We will look at how each one works with simple examples.
1// Using const for a value that won't change2const userName = "Alice"; // 'userName' is set to "Alice" and cannot be changed.34// Using let for a value that might change5let userScore = 100; // 'userScore' is set to 100.6userScore = 120; // We can change 'userScore' later to 120.78// Using var (older way, generally avoided)9var gameLevel = 1; // 'gameLevel' is set to 1.10gameLevel = 2; // We can also change 'gameLevel' later to 2.1112console.log(userName); // Shows: Alice13console.log(userScore); // Shows: 12014console.log(gameLevel); // Shows: 2
The Biggest Beginner Mistake: Not Understanding Scope
Many beginners use var without realizing its special rules about scope. Scope means where your variable can be seen and used in your code. Using var can make variables available in unexpected places, leading to confusing bugs. Always think about scope when declaring variables.
Why `const` and `let` are Better
Why `const` and `let` are Better
The main reason const and let are better is how they handle scope and how they let you re-assign or re-declare variables. const and let use 'block scope'. This means a variable declared inside a code block (like an if statement or a for loop) can only be used inside that block. var uses 'function scope', which is less strict and can cause problems.
1// --- const example ---2const appName = "My App";3// appName = "New App"; // This would cause an error! You cannot re-assign a const variable.45// --- let example ---6let counter = 0;7function increment() {8 counter = counter + 1; // You can re-assign a let variable.9 console.log("Inside function (let):", counter); // Shows 110}11increment();12console.log("Outside function (let):", counter); // Shows 11314// --- var example (problematic scope) ---15var globalMessage = "Hello";16if (true) {17 var globalMessage = "Hi there"; // This re-declares the SAME 'globalMessage' variable.18 console.log("Inside if (var):", globalMessage); // Shows: Hi there19}20console.log("Outside if (var):", globalMessage); // Shows: Hi there (unexpectedly changed)2122let blockMessage = "Hello";23if (true) {24 let blockMessage = "Hi there"; // This creates a NEW 'blockMessage' just for this block.25 console.log("Inside if (let):", blockMessage); // Shows: Hi there26}27console.log("Outside if (let):", blockMessage); // Shows: Hello (original value, not changed)
var x = 10;console.log(x); // 10if (true) {var x = 20; // This re-declares the *same* 'x'console.log(x); // 20}console.log(x); // 20 (Unexpected! 'x' changed outside the block)
let y = 10;console.log(y); // 10if (true) {let y = 20; // This creates a *new* 'y' for this blockconsole.log(y); // 20}console.log(y); // 10 (Expected! 'y' outside the block is unchanged)
Choosing the Right Keyword
Choosing the Right Keyword
Deciding between const and let is a simple rule. Always try to use const first. If you later realize that the value stored in the variable needs to change, then you can switch it to let. This approach helps prevent accidental changes to your data and makes your code more robust.
// Start with const for everythingconst productName = "Laptop";const itemPrice = 999.99;let totalItems = 0; // Oh, wait, this will change!// Later, if you need to update it, change to lettotalItems = 5; // This is fine with let// itemPrice = 1000; // Error! 'itemPrice' is const
// Declare with let only if you know it will changelet currentTemperature = 25; // Temperature changescurrentTemperature = 27;// Declare with const if it won'tconst cityName = "New York"; // City name is constant// cityName = "London"; // Error!
// Start with const for everythingconst productName = "Laptop";const itemPrice = 999.99;let totalItems = 0; // Oh, wait, this will change!// Later, if you need to update it, change to lettotalItems = 5; // This is fine with let// itemPrice = 1000; // Error! 'itemPrice' is const
// Declare with let only if you know it will changelet currentTemperature = 25; // Temperature changescurrentTemperature = 27;// Declare with const if it won'tconst cityName = "New York"; // City name is constant// cityName = "London"; // Error!
The Golden Rule for Variables
Always use const by default. This tells everyone that this value should not change. If you absolutely need to change the variable's value later, then use let. Never use var in new JavaScript code.
Applying Best Practices in Your Code
Applying Best Practices in Your Code
Putting these rules into practice will make your code much better. It helps prevent bugs and makes your code easier for others (and your future self!) to understand. Follow these steps every time you declare a new variable.
Step 1: Start with `const`
When you need a new variable, always begin by declaring it with const. This is your default choice. It's safer because it prevents accidental changes.
1const userName = "Jane Doe";2const maxAttempts = 3;
Step 2: Change to `let` if Re-assignment is Needed
If you later find that the value of your variable needs to change during the program's execution, then—and only then—change const to let. Remember, const prevents re-assignment.
1let score = 0; // Starts at 0, will change2score = score + 10; // Value is updated34let timerId; // Will store a timer ID later5timerId = setTimeout(() => console.log('Time up!'), 1000);
Step 3: Use Descriptive Names
Give your variables names that clearly explain what they hold. Avoid single-letter names like x or y unless it's a simple loop counter. Good names make your code much easier to read and understand.
1// Bad name2const a = 10;34// Good name5const userAge = 10; // Much clearer what 'userAge' means
Step 4: Declare Variables Close to Their Use
Try to declare variables as close as possible to where they are first used. This improves readability and helps you manage scope better. It also makes your code more organized.
1function calculateTotal(price, quantity) {2 const taxRate = 0.05; // Declared right before use3 const subtotal = price * quantity;4 const total = subtotal * (1 + taxRate);5 return total;6}
What Breaks if You Ignore These Rules?
Ignoring these best practices can lead to hard-to-find bugs. If you use var, your variables might accidentally change their values in unexpected parts of your code. If you use let when const would be better, you lose a layer of safety that prevents accidental data modification, making your program less reliable.
Variable Declaration Quick Reference
Variable Declaration Quick Reference
| Feature | `var` | `let` | `const` |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Can Re-assign? | Yes | Yes | No (for primitives) |
| Can Re-declare? | Yes | No (in same scope) | No (in same scope) |
| Hoisting Behavior | Hoisted and initialized with `undefined` | Hoisted, but in Temporal Dead Zone (TDZ) | Hoisted, but in Temporal Dead Zone (TDZ) |
Test Your Knowledge
Test Your Knowledge
Which keyword should you use by default when declaring a variable whose value is not expected to change?
What happens if you try to re-assign a variable declared with const?
Which variable declaration keyword has 'function scope'?
Which of these is considered a best practice for naming variables?
Quick Reference
Quick Reference
- 1
constDefault — Always start by declaring variables withconstunless you know their value will change. - 2
letfor Change — Useletonly when you expect the variable's value to be re-assigned later in your code. - 3Avoid
var— Steer clear ofvarin modern JavaScript due to its confusing function scope and hoisting behavior. - 4Block Scope —
letandconstare block-scoped, meaning they are only available within the code block they are defined in. - 5Function Scope —
varis function-scoped, which can lead to variables being accessible in unexpected places. - 6No Re-assignment for
const— Once aconstvariable is assigned a primitive value, it cannot be changed. For objects, the object's properties can still be modified. - 7No Re-declaration — You cannot re-declare
letorconstvariables in the same scope, preventing accidental overwrites. - 8Descriptive Naming — Choose variable names that clearly explain what the variable holds, like
userNameinstead ofu. - 9Declare Locally — Declare variables as close as possible to where they are first used to improve code readability and maintain scope.
- 10Readability & Maintainability — Following these best practices makes your code easier to read, debug, and maintain for everyone.
JavaScript Data Types
Learn about the different kinds of data you can store in variables, like numbers, strings, and booleans.
Understanding Scope
Dive deeper into how scope works in JavaScript and why it's so important for managing variables.
Control Flow (if/else)
Explore how to make decisions in your code using if, else if, and else statements.
Functions in JavaScript
Discover how to group code into reusable blocks using functions to make your programs more organized.
Congratulations!
You've learned the essential best practices for declaring variables in JavaScript. By consistently using const and let correctly, you are building a strong foundation for writing clean, robust, and error-resistant code. Keep practicing these habits, and your JavaScript skills will grow quickly!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.