Sitemap

Understanding var, let, and const

5 min readSep 23, 2024

--

Press enter or click to view image in full size
Javascript book on table

Question

What are the differences between var,let and const

Answer:

They are all ways to initialize variables but differ in a few ways:

  1. Scope
  2. Initialization
  3. Redeclaration
  4. Reassignment
  5. Hoisting
Accessing before declaration

+-------------------------------+--------------------+--------------------+--------------------+
| Behavior | var | let | const |
+-------------------------------+--------------------+--------------------+--------------------+
| Scope | Function or Global | Block | Block |
| Initialization | Optional | Optional | Required |
| Redeclaration | Yes | No | No |
| Reassignment | Yes | Yes | No |
| Accessing before declaration | undefined | ReferenceError | ReferenceError |
+-------------------------------+--------------------+--------------------+--------------------+

TLDR: By default use const use let if you need to reassign and stay away from var

Scope

When var is function scoped. You can access it throughout the function, regardless of any other blocks.

// 🔍 Example: Function Scope in a React Component
function UserProfile() {
if (true) {
var userName = 'Alice'; // var is function scoped
}

// ✅ Accessible here because var is function scoped
console.log(userName); // Output: Alice

return <div>{userName}</div>;
}

console.log(userName); // ❌ ReferenceError: userName is not defined

Global Scope with var

// 🌐 Example: Global Scope with var
// Declared in the global scope
var appName = 'MyReactApp';

function showAppName() {
console.log(appName); // ✅ Accessible here
}

showAppName(); // Output: MyReactApp

// ✅ Accessible globally
console.log(appName); // Output: MyReactApp

// 🚫 Important Note 🚫:
// Declaring variables with var in the global scope can
// lead to potential conflicts and unintended side effects.
// It's generally recommended to minimize the use of global variables.

Block Scope: Variables declared with let and const are only accessible within the nearest set of curly braces {}—such as inside loops, conditionals, or blocks.

// 🔍 Example: Block Scope in Conditional Rendering
function Dashboard({ isAdmin }) {
if (isAdmin) {
let adminPanel = <AdminPanel />; // ✅ let is block scoped
const adminMessage = 'Welcome, Admin!'; // ✅ const is block scoped

console.log(adminPanel); // ✅ Accessible here
console.log(adminMessage); // ✅ Accessible here
}

// ❌ console.log(adminPanel); // ReferenceError: adminPanel is not defined
// ❌ console.log(adminMessage); // ReferenceError: adminMessage is not defined

return <div>Dashboard Content</div>;
}

Global Scope: When let and const are used in the global scope, they do not attach to the global object, preventing accidental global variable leaks.

// 🌐 Example: Global Scope with let and const
// Declared in the global scope
let appVersion = '1.0.0';
const appAuthor = 'John Doe';

function showAppDetails() {
console.log(appVersion); // ✅ Accessible here
console.log(appAuthor); // ✅ Accessible here
}

showAppDetails(); // Output: 1.0.0, John Doe

// ✅ Accessible globally
console.log(appVersion); // Output: 1.0.0
console.log(appAuthor); // Output: John Doe

// ❌ However, they do NOT attach to the window object
console.log(window.appVersion); // undefined
console.log(window.appAuthor); // undefined

Initialization

You can declare var and let variables without assigning them a value immediately.

Get Gurjeet Matharu’s stories in your inbox

Join Medium for free to get updates from this writer.

// 📝 Example: Handling User Input in React with let
function SearchBar() {
let query; // ✅ Declared without initialization

const handleSearch = () => {
query = 'React Hooks'; // ✅ Assigned later
console.log(query); // Output: React Hooks
};

return <button onClick={handleSearch}>Search</button>;
}

Variables declared with const must be assigned a value at the time of declaration.

// 📝 Example: Immutable Configuration in React with const
function AppConfig() {
const API_ENDPOINT = 'https://api.example.com'; // ✅ Must initialize here

// ❌ API_ENDPOINT = 'https://api.newexample.com'; // Error: Assignment to constant variable.

return <div>API Endpoint: {API_ENDPOINT}</div>;
}

Redeclaration

Using var, you can declare the same variable multiple times within the same scope without errors.

// 🔄 Example: Redeclaration with var
function initializeSettings() {
var theme = 'dark';
var theme = 'light'; // ✅ No error, theme is now 'light'

console.log(theme); // Output: light
}

Attempting to redeclare a let or const variable in the same scope will throw an error.

// 🔄 Example: Preventing Redeclaration with let and const
function initializeSettings() {
let theme = 'dark';
// ❌ let theme = 'light'; // Error: Identifier 'theme' has already been declared

const API_KEY = '12345';
// ❌ const API_KEY = '67890'; // Error: Identifier 'API_KEY' has already been declared

console.log(theme, API_KEY); // Output: dark 12345
}

Reassignment

You can change the value of variables declared with var and let.

// 🔄 Example: Reassignment with let
function Timer() {
let count = 0;

const increment = () => {
count += 1;
console.log(count); // Outputs: 1, 2, 3, ...
};

return <button onClick={increment}>Increment</button>;
}

Once a const variable is set, its value cannot be changed.

// 🔒 Example: Immutability with const
function Constants() {
const MAX_USERS = 100;

// ❌ MAX_USERS = 150; // Error: Assignment to constant variable.

return <div>Maximum Users: {MAX_USERS}</div>;
}

Note: If a const holds an object or array, the contents can be modified, but the reference cannot be changed

// 🔒 Example: Modifying Object Properties with const
const settings = { theme: 'dark' };
settings.theme = 'light'; // ✅ Allowed: Modifies property
// ❌ settings = { theme: 'light' }; // Error: Assignment to constant variable.

Hoisting

Variables declared with var are moved to the top of their functional scope and initialized with undefined. This means you can access them before their declaration without a ReferenceError, but they'll be undefined.

// 📈 Example: Hoisting with var
function fetchData() {
console.log(apiUrl); // Output: undefined
var apiUrl = 'https://api.example.com';

console.log(apiUrl); // Output: https://api.example.com
}

Variables declared with let and const are hoisted but not initialized. Accessing them before their declaration results in a ReferenceError due to the "temporal dead zone."

// 🕰️ Example: Temporal Dead Zone with let and const
function loadConfig() {
// ❌ console.log(config); // ReferenceError: Cannot access 'config' before initialization
let config = { env: 'production' };

console.log(config); // Output: { env: 'production' }
}

Summary

  • var is function or global scoped, attaches to the global object, can be redeclared and reassigned, and is hoisted as undefined.
  • let and const are block or global scoped, do not attach to the global object, and cannot be redeclared.
  • let allows reassignment; const does not (except for object properties).
  • Both let and const are hoisted but remain in the Temporal Dead Zone until initialized.

--

--