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:
- ES5 and earlier: Only one declaration method
var - ES6 (ES2015): Introduced
letandconst - Modern JavaScript: Recommends using
letandconst, avoidingvar
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
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
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 defined2. Hoisting
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
var a = 1;
var a = 2; // No error
console.log(a); // 2let Declaration
let is the block-scoped variable declaration method introduced in ES6, solving some problems with var.
Basic Usage
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
function example() {
if (true) {
let x = 1;
}
// console.log(x); // ReferenceError: x is not defined
}
example();2. Temporal Dead Zone (TDZ)
console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = "Jane";
// Variables declared with let are not accessible before declaration3. Cannot Be Redeclared
let a = 1;
// let a = 2; // SyntaxError: Identifier 'a' has already been declared4. Scope in Loops
// 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
const PI = 3.14159;
const NAME = "Alice";
const IS_ACTIVE = true;
// Must be initialized at declaration
// const AGE; // SyntaxError: Missing initializer in const declarationCharacteristics of const
1. Must Be Initialized
const name = "Bob"; // Correct
// const age; // Error: must be initialized2. Cannot Be Reassigned
const MAX_SIZE = 100;
// MAX_SIZE = 200; // TypeError: Assignment to constant variable.3. Block Scope
if (true) {
const MESSAGE = "Hello";
}
// console.log(MESSAGE); // ReferenceError: MESSAGE is not defined4. Special Cases with Objects and Arrays
// 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
- Prefer
const: When the variable doesn't need to be reassigned - Use
letwhen necessary: When the variable needs to be reassigned - Avoid
var: Unless you need to support older browsers
// 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
// 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
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); // 5let and const Hoisting
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
const globalVar = "Global variable";
function example() {
console.log(globalVar); // Accessible
}Function Scope
function outer() {
var functionVar = "Function scope variable";
function inner() {
console.log(functionVar); // Accessible
}
inner();
}Block Scope
{
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); // ReferenceErrorVariable Naming Conventions
Naming Rules
// 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 keywordsNaming Conventions
// 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
// Good practice
const users = [];
const config = {};
// Use let when reassignment is needed
let currentUser = null;
if (isLoggedIn) {
currentUser = getUserInfo();
}2. Avoid Global Variable Pollution
// 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
// 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:
Three Declaration Methods:
var: Function scope, can be redeclared, hoisting existslet: Block scope, cannot be redeclared, temporal dead zone existsconst: Block scope, cannot be reassigned, must be initialized
Modern Recommended Practices:
- Prefer
const, useletwhen necessary - Avoid using
var
- Prefer
Scope Concepts:
- Global scope
- Function scope (var)
- Block scope (let, const)
Hoisting:
- var hoists declaration but not assignment
- let and const hoist but have temporal dead zone
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.