Skip to content

JavaScript Variable Declaration

Variables are one of the most fundamental concepts in programming languages, used to store and manipulate data. In JavaScript, variable declaration is an important topic because it involves scope, lifecycle, and memory management. In this chapter, we will learn in depth about variable declaration methods and their characteristics in JavaScript.

Historical Evolution of Variable Declaration

The way variables are declared in JavaScript has evolved with the language:

  1. ES5 and earlier: Only one declaration method var
  2. ES6 (ES2015): Introduced let and const
  3. Modern JavaScript: Recommends using let and const, avoiding var

var Declaration

var is the earliest variable declaration method in JavaScript, but it has some special characteristics and is generally not recommended for use today.

Basic Usage

javascript
var name = "John";
var age = 25;
var isStudent = true;

// Can declare multiple variables
var x = 1, y = 2, z = 3;

// Can declare first and assign later
var greeting;
greeting = "Hello";

Characteristics of var

1. Function Scope

javascript
function example() {
    if (true) {
        var x = 1;
    }
    console.log(x); // 1 (accessible)
}

example();

// Cannot access outside block scope
// console.log(x); // ReferenceError: x is not defined

2. Hoisting

javascript
console.log(name); // undefined (not an error)
var name = "John";
console.log(name); // "John"

// The above code is actually equivalent to:
// var name;
// console.log(name); // undefined
// name = "John";
// console.log(name); // "John"

3. Can Be Redeclared

javascript
var a = 1;
var a = 2; // No error
console.log(a); // 2

let Declaration

let is the block-scoped variable declaration method introduced in ES6, solving some problems with var.

Basic Usage

javascript
let name = "Jane";
let age = 30;
let isEmployed = true;

// Can declare multiple variables
let x = 1, y = 2, z = 3;

// Can declare first and assign later
let greeting;
greeting = "Hello";

Characteristics of let

1. Block Scope

javascript
function example() {
    if (true) {
        let x = 1;
    }
    // console.log(x); // ReferenceError: x is not defined
}

example();

2. Temporal Dead Zone (TDZ)

javascript
console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = "Jane";

// Variables declared with let are not accessible before declaration

3. Cannot Be Redeclared

javascript
let a = 1;
// let a = 2; // SyntaxError: Identifier 'a' has already been declared

4. Scope in Loops

javascript
// Using var
for (var i = 0; i < 3; i++) {
    setTimeout(() => {
        console.log("var:", i); // Outputs "var: 3" three times
    }, 100);
}

// Using let
for (let j = 0; j < 3; j++) {
    setTimeout(() => {
        console.log("let:", j); // Outputs "let: 0", "let: 1", "let: 2"
    }, 100);
}

const Declaration

const is used to declare constants that cannot be reassigned once declared.

Basic Usage

javascript
const PI = 3.14159;
const NAME = "Alice";
const IS_ACTIVE = true;

// Must be initialized at declaration
// const AGE; // SyntaxError: Missing initializer in const declaration

Characteristics of const

1. Must Be Initialized

javascript
const name = "Bob"; // Correct
// const age; // Error: must be initialized

2. Cannot Be Reassigned

javascript
const MAX_SIZE = 100;
// MAX_SIZE = 200; // TypeError: Assignment to constant variable.

3. Block Scope

javascript
if (true) {
    const MESSAGE = "Hello";
}
// console.log(MESSAGE); // ReferenceError: MESSAGE is not defined

4. Special Cases with Objects and Arrays

javascript
// The object itself cannot be reassigned, but properties can be modified
const person = { name: "John", age: 25 };
person.age = 26; // Correct
console.log(person.age); // 26

// person = { name: "Jane" }; // Error: Assignment to constant variable.

// Same for arrays
const numbers = [1, 2, 3];
numbers.push(4); // Correct
console.log(numbers); // [1, 2, 3, 4]

// numbers = [5, 6, 7]; // Error: Assignment to constant variable.

Choosing Declaration Methods

Modern JavaScript Best Practices

  1. Prefer const: When the variable doesn't need to be reassigned
  2. Use let when necessary: When the variable needs to be reassigned
  3. Avoid var: Unless you need to support older browsers
javascript
// Good practice
const userName = "John"; // Won't change
let userAge = 25;        // Might change
userAge = 26;            // Correct

// Not recommended
var oldStyle = "Outdated approach";

Practical Application Examples

javascript
// Configuration constants
const API_URL = "https://api.example.com";
const MAX_RETRY_COUNT = 3;

// Loop variable
for (let i = 0; i < 10; i++) {
    console.log(i);
}

// Conditional variable
let isLoggedIn = false;
if (someCondition) {
    isLoggedIn = true;
}

// Object reference
const config = {
    theme: "dark",
    language: "en-US"
};

// Properties can be modified
config.theme = "light";

Hoisting

Hoisting is the way JavaScript execution context works.

var Hoisting

javascript
console.log(a); // undefined
var a = 5;
console.log(a); // 5

// Actual execution order:
// var a;
// console.log(a); // undefined
// a = 5;
// console.log(a); // 5

let and const Hoisting

javascript
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 10;

console.log(c); // ReferenceError: Cannot access 'c' before initialization
const c = 15;

Scope

Scope determines the accessibility range of variables.

Global Scope

javascript
const globalVar = "Global variable";

function example() {
    console.log(globalVar); // Accessible
}

Function Scope

javascript
function outer() {
    var functionVar = "Function scope variable";
    
    function inner() {
        console.log(functionVar); // Accessible
    }
    
    inner();
}

Block Scope

javascript
{
    let blockVar = "Block scope variable";
    const blockConst = "Block scope constant";
    
    console.log(blockVar); // Accessible
    console.log(blockConst); // Accessible
}

// console.log(blockVar); // ReferenceError
// console.log(blockConst); // ReferenceError

Variable Naming Conventions

Naming Rules

javascript
// Correct naming
let userName = "John";
let $price = 99.99;
let _private = "Private variable";
let camelCase = "Camel case naming";

// Incorrect naming
// let 123name = "Error"; // Cannot start with a number
// let my-variable = "Error"; // Cannot contain hyphens
// let let = "Error"; // Cannot use reserved keywords

Naming Conventions

javascript
// Regular variables use camelCase
let firstName = "John";
let lastName = "Doe";

// Constants use uppercase letters and underscores
const MAX_SIZE = 100;
const DEFAULT_CONFIG = {
    theme: "light",
    language: "en-US"
};

// Private variables start with underscore (convention)
let _internalValue = "Internal use";

// Constructor functions use PascalCase
function UserManager() {
    // Constructor body
}

Best Practices for Variable Declaration

1. Prefer const Principle

javascript
// Good practice
const users = [];
const config = {};

// Use let when reassignment is needed
let currentUser = null;
if (isLoggedIn) {
    currentUser = getUserInfo();
}

2. Avoid Global Variable Pollution

javascript
// Bad practice
var globalCounter = 0;

// Good practice
const App = {
    counter: 0
};

// Or use modules
const counterModule = (() => {
    let counter = 0;
    
    return {
        increment() {
            counter++;
        },
        getValue() {
            return counter;
        }
    };
})();

3. Group Declarations Appropriately

javascript
// Related variables can be declared together
const WIDTH = 800;
const HEIGHT = 600;
const ASPECT_RATIO = WIDTH / HEIGHT;

// Unrelated variables declared separately
const userName = "John";
let userAge = 25;
const isLoggedIn = true;

Summary

Key points about JavaScript variable declaration:

  1. Three Declaration Methods:

    • var: Function scope, can be redeclared, hoisting exists
    • let: Block scope, cannot be redeclared, temporal dead zone exists
    • const: Block scope, cannot be reassigned, must be initialized
  2. Modern Recommended Practices:

    • Prefer const, use let when necessary
    • Avoid using var
  3. Scope Concepts:

    • Global scope
    • Function scope (var)
    • Block scope (let, const)
  4. Hoisting:

    • var hoists declaration but not assignment
    • let and const hoist but have temporal dead zone
  5. Naming Conventions:

    • Use meaningful variable names
    • Follow camelCase naming convention
    • Use uppercase for constants

Mastering variable declaration is an important foundation for learning JavaScript. In the next chapter, we will learn about JavaScript objects.

Content is for learning and research only.