javascript

Best Practices for Variable Declaration

Learn the best ways to declare variables in JavaScript using `const` and `let`. Understand scope, re-assignment, and re-declaration to write cleaner, more reliable code.

10 min read 8 sections Tutorial
Share

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`

Getting Started

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.

javascript
1// Using const for a value that won't change
2const userName = "Alice"; // 'userName' is set to "Alice" and cannot be changed.
3
4// Using let for a value that might change
5let userScore = 100; // 'userScore' is set to 100.
6userScore = 120; // We can change 'userScore' later to 120.
7
8// Using var (older way, generally avoided)
9var gameLevel = 1; // 'gameLevel' is set to 1.
10gameLevel = 2; // We can also change 'gameLevel' later to 2.
11
12console.log(userName); // Shows: Alice
13console.log(userScore); // Shows: 120
14console.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.

javascript
1// --- const example ---
2const appName = "My App";
3// appName = "New App"; // This would cause an error! You cannot re-assign a const variable.
4
5// --- 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 1
10}
11increment();
12console.log("Outside function (let):", counter); // Shows 1
13
14// --- 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 there
19}
20console.log("Outside if (var):", globalMessage); // Shows: Hi there (unexpectedly changed)
21
22let 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 there
26}
27console.log("Outside if (let):", blockMessage); // Shows: Hello (original value, not changed)
✗ BadProblem with `var`
var x = 10;
console.log(x); // 10
if (true) {
var x = 20; // This re-declares the *same* 'x'
console.log(x); // 20
}
console.log(x); // 20 (Unexpected! 'x' changed outside the block)
✓ GoodSolution with `let`
let y = 10;
console.log(y); // 10
if (true) {
let y = 20; // This creates a *new* 'y' for this block
console.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.

Always `const` First
// Start with const for everything
const productName = "Laptop";
const itemPrice = 999.99;
let totalItems = 0; // Oh, wait, this will change!
// Later, if you need to update it, change to let
totalItems = 5; // This is fine with let
// itemPrice = 1000; // Error! 'itemPrice' is const
VS
Use `let` When Values Change
// Declare with let only if you know it will change
let currentTemperature = 25; // Temperature changes
currentTemperature = 27;
// Declare with const if it won't
const 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.

1

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.

javascript
1const userName = "Jane Doe";
2const maxAttempts = 3;
2

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.

javascript
1let score = 0; // Starts at 0, will change
2score = score + 10; // Value is updated
3
4let timerId; // Will store a timer ID later
5timerId = setTimeout(() => console.log('Time up!'), 1000);
3

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.

javascript
1// Bad name
2const a = 10;
3
4// Good name
5const userAge = 10; // Much clearer what 'userAge' means
4

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.

javascript
1function calculateTotal(price, quantity) {
2 const taxRate = 0.05; // Declared right before use
3 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`
ScopeFunction-scopedBlock-scopedBlock-scoped
Can Re-assign?YesYesNo (for primitives)
Can Re-declare?YesNo (in same scope)No (in same scope)
Hoisting BehaviorHoisted and initialized with `undefined`Hoisted, but in Temporal Dead Zone (TDZ)Hoisted, but in Temporal Dead Zone (TDZ)

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which keyword should you use by default when declaring a variable whose value is not expected to change?

Quick Check

What happens if you try to re-assign a variable declared with const?

Quick Check

Which variable declaration keyword has 'function scope'?

Quick Check

Which of these is considered a best practice for naming variables?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1const Default — Always start by declaring variables with const unless you know their value will change.
  • 2let for Change — Use let only when you expect the variable's value to be re-assigned later in your code.
  • 3Avoid var — Steer clear of var in modern JavaScript due to its confusing function scope and hoisting behavior.
  • 4Block Scopelet and const are block-scoped, meaning they are only available within the code block they are defined in.
  • 5Function Scopevar is function-scoped, which can lead to variables being accessible in unexpected places.
  • 6No Re-assignment for const — Once a const variable 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 let or const variables in the same scope, preventing accidental overwrites.
  • 8Descriptive Naming — Choose variable names that clearly explain what the variable holds, like userName instead of u.
  • 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.

Continue Learning