search ]

JavaScript Variables and Constants for Beginners

JavaScript Variables and Constants are fundamental to any script. They are used to store data values that can be retrieved and manipulated later. This post will explore how to declare and use variables and constants in JavaScript with practical examples.

What Are JavaScript Variables and How to Declare Them?

In JavaScript, variables are like containers that hold information. You can declare a variable using one of three keywords: var, let, or const. Let’s look at each one:

Using var

The var keyword is the oldest way to declare a variable. It has a function scope, meaning it’s accessible anywhere within the function where it’s defined.

var name = 'John Doe';
console.log(name); // Output: John Doe

var name = 'Jane Doe'; // Re-declare the same variable
console.log(name); // Output: Jane Doe

Note: Re-declaring variables with var can lead to unexpected behavior, especially in large scripts, since the variable can be unintentionally overwritten.

Using let

The let keyword is a newer and better way to declare variables. It has block scope, meaning it’s only accessible within the block (e.g., within curly braces) where it’s defined.

let age = 25;
console.log(age); // Output: 25

age = 26; // Update the variable
console.log(age); // Output: 26

// let age = 30; // Error: You cannot re-declare a variable with let in the same scope

Using const

The const keyword is used to declare a constant, meaning the value cannot be reassigned after it’s set. Like let, it also has block scope.

const birthYear = 1995;
console.log(birthYear); // Output: 1995

// birthYear = 2000; // Error: You cannot reassign a constant

Note: If the value assigned to a const is an object or array, its properties can still be changed:

const person = { name: 'John' };
person.name = 'Jane'; // Works - modifying a property, not reassigning
console.log(person.name); // Output: Jane

// person = { name: 'Bob' }; // Error - reassigning the variable itself

Tip for Beginners: Always use const unless you know the value will change. It helps prevent accidental changes and makes your code easier to understand.

Understanding Variable Scope

Scope determines where you can access your variables in your code. Let’s break it down:

  • Global Scope: Variables declared outside any function can be used anywhere in your code.
  • Function Scope: Variables declared with var inside a function are only available within that function.
  • Block Scope: Variables declared with let or const are only available within the block they’re defined in.
var globalVar = 'I am global';

function testVar() {
    var functionVar = 'I am a function variable';
    console.log(globalVar);   // Accessible
    console.log(functionVar); // Accessible
}

if (true) {
    let blockVar = 'I am a block variable';
    console.log(blockVar); // Accessible inside the block
}

testVar();
// console.log(functionVar); // Error: functionVar is not defined outside the function
// console.log(blockVar); // Error: blockVar is not defined outside the block

In the above example, globalVar is accessible globally, functionVar is accessible only within the testVar function, and blockVar is accessible only within the block where it is declared.

Hoisting and the Temporal Dead Zone

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compile phase. However, only the declarations are hoisted – not the initializations.

The way hoisting works differs between var, let, and const:

// var is hoisted and initialized as undefined
console.log(a); // undefined (no error)
var a = 10;

// let and const are hoisted but NOT initialized
// Accessing them before declaration throws a ReferenceError
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;

The period between entering a block scope and the line where let or const is declared is called the Temporal Dead Zone (TDZ). During this time, the variable exists but cannot be accessed:

{
    // TDZ starts here for 'x'
    // console.log(x); // ReferenceError
    let x = 42; // TDZ ends - 'x' is now initialized
    console.log(x); // 42
}

The var Pitfall in Loops

A common and confusing bug with var occurs in loops, because var does not create a new scope for each iteration:

// Problem with var
for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (not 0, 1, 2!)

// Solution with let
for (let j = 0; j < 3; j++) {
    setTimeout(() => console.log(j), 100);
}
// Output: 0, 1, 2 (correct!)

With var, there is only one i variable shared across all iterations. By the time the setTimeout callbacks execute, the loop has finished and i is 3. With let, each iteration gets its own scoped copy of j, preserving the correct value.

Key Differences Between var, let, and const

The following table compares the behavior of JavaScript’s var, let, and const by key properties such as scope, re-declaration, and re-assignment:

Propertyvarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Re-declarationAllowedNot allowedNot allowed
Re-assignmentAllowedAllowedNot allowed
HoistingYes, initialized with undefinedYes, but in TDZ until declaredYes, but in TDZ until declared
InitializationOptionalOptionalRequired
Use in loopsNot suited for loops due to scope issuesBest suited for loopsWorks in loops but value cannot be reassigned

Rules for Naming JavaScript Variables

Naming variables in JavaScript follows specific rules to ensure clarity and avoid errors:

  • Begin with a Letter, Underscore, or Dollar Sign: Variable names must start with a letter, an underscore (_), or a dollar sign ($).
  • Case-Sensitive: Variable names are case-sensitive, meaning name and Name are different variables.
  • No Reserved Keywords: Variable names cannot be reserved keywords like var, function, or class.
  • Use CamelCase for Multi-word Names: Use camelCase for variable names that consist of multiple words.
let firstName = 'John';     // camelCase
let _private = 'secret';    // starts with underscore
let $price = 20;            // starts with dollar sign
// let var = 'value';       // Error: reserved keyword

Best Practices

Here are some best practices when using variables and constants in JavaScript:

  • Use const by default. It ensures your variables cannot be reassigned, leading to fewer bugs and a more predictable codebase.
  • Use let for values that change – such as loop counters, accumulator values, or conditional state.
  • Avoid var in modern code. Its function-scoped behavior and hoisting quirks can lead to unexpected bugs.
  • Declare variables at the top of their scope. This makes the code easier to read and avoids TDZ-related confusion.
  • Use descriptive names. Choose clear, meaningful variable names like userAge rather than x or temp.

FAQs

Common questions about JavaScript variables and constants:

Should I use var, let, or const?
Use const by default for any value that won't be reassigned. Use let when you need to reassign a value, such as loop counters or accumulator variables. Avoid var in modern JavaScript - its function-scoped behavior and hoisting quirks cause subtle bugs. Using const as your default communicates intent and prevents accidental reassignment.
What is the Temporal Dead Zone (TDZ)?
The Temporal Dead Zone is the period between entering a block scope and the point where a let or const variable is declared. During this time, the variable exists but cannot be accessed - attempting to use it throws a ReferenceError. This behavior catches bugs where you accidentally use a variable before declaring it, unlike var which silently returns undefined.
Can I change properties of a const object?
Yes. const prevents reassignment of the variable itself, but it does not make the value immutable. If a const holds an object or array, you can still modify its properties or elements. For example, const arr = [1, 2]; arr.push(3); works fine. What you cannot do is reassign the variable: arr = [4, 5]; throws an error. To make an object truly immutable, use Object.freeze().
What is hoisting in JavaScript?
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope during compilation. With var, the declaration is hoisted and initialized as undefined, so accessing it before the declaration line returns undefined instead of an error. With let and const, declarations are hoisted but not initialized, creating a Temporal Dead Zone where access throws a ReferenceError.
Why does var behave differently in loops?
Because var is function-scoped, not block-scoped. In a for loop, var creates a single variable shared across all iterations. By the time asynchronous callbacks (like setTimeout) execute, the loop has finished and the variable holds its final value. With let, each iteration gets its own block-scoped copy of the variable, preserving the correct value for each callback.
What are the rules for naming variables in JavaScript?
Variable names must start with a letter, underscore (_), or dollar sign ($). They are case-sensitive (name and Name are different). They cannot use reserved keywords like var, function, or class. The convention in JavaScript is to use camelCase for multi-word names (like firstName, totalPrice). Choose descriptive names that make the code self-documenting.

Conclusion

Variables and constants are fundamental to programming in JavaScript. Understanding the differences between var, let, and const, as well as their scope and hoisting behavior, is crucial for writing clean and efficient code.

For a deeper dive into common errors and how to prevent them, check out the post on How to Avoid Common Mistakes with JavaScript Variables. For more JavaScript fundamentals, explore the guides on strings, operators, and functions.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo