Variables in JavaScript (var, let, const)

Learn how to declare, assign, and initialize variables in JavaScript using var, let, and const. Understand the key differences in scope, hoisting, shadowing, and best practices for variable usage with clear examples.
Variables in JavaScript
In JavaScript, variables are used to store and manipulate data. They can hold values of various types, such as numbers, strings, Booleans, or objects.
Let's understand variable configuration:
1. Declaration
-
Declaration is the process of defining a variable name without assigning a value to it.
-
Example:
var name;In this example, var is a keyword used for declaring variables, and name is the name of the variable being declared.
2. Assignment
- Assignment is the process of assigning a value to a variable after it has been declared.
- Example:
name = "coders";Here, the variable name is assigned the value "coders".
3. Initialization
- Initialization is the process of assigning an initial value to a variable at the time of declaration.
- Example:
var age = 25;Here, the variable age is declared and initialized with the value 25.
To display this value, you can use:
var age = 25;
document.write("age = " + age);This will output:
age = 25
Reassigning Values
- After a variable has been initialized, you can change its value by reassigning it.
- Example:
var age = 25;
age = 30;
document.write("age = " + age);Now, age is 30.
Variables Without Declaration (Non-Strict Mode)
- In JavaScript, you can initialize a variable without explicitly declaring it if the code is not in strict mode.
- Example:
marks = 90; // No 'var', 'let', or 'const'This will display the value of marks as 90.
Strict Mode Restriction
- However, when you use strict mode, declaring a variable without a keyword will result in an error.
- Example:
"use strict";
marks = 90; // Error: marks is not definedIn this case, JavaScript requires all variables to be declared properly using var, let, or const.
1. var
- Variables declared with
varhave function-level scope or global scope if declared outside of any function.
Function-Level Scope Example:
function show() {
var age; // Variable declaration
age = 30; // Variable assignment
if (age === 30) {
var msg = "welcome"; // Declared inside a block but has function scope
}
document.write("message = " + msg); // Valid and shows "message = welcome"
}In this example:
- The variable
msgis declared inside theifcondition block but is accessible outside of it becausevarhas function-level scope.
Variable Shadowing:
varsupports shadowing, which means you can redeclare a variable without causing an error.- Example:
var msg = "welcome";
var msg = "welcome to club"; // Re-declared without any error
document.write("message = " + msg); // Outputs: "message = welcome to club"Here, the second declaration of msg with a new value replaces the original value without any errors.
Hoisting:
varsupports hoisting, meaning you can use the variable before it has been declared.- Example:
x = 20; // Initialized without declaration
document.write("x = " + x); // Outputs: "x = 20"
var x; // Declaration (hoisted to the top)In this case:
- Even though the variable
xis initialized before it is declared, JavaScript moves the declaration to the top during compilation, making it accessible throughout the function or globally if outside any function.
2. let
- Variables declared with
lethave block-level scope, meaning they are limited to the block enclosed by curly braces.
Block-Level Scope Example:
function show() {
let age = 30; // Variable declared with let
if (age === 30) {
let ticket = 123; // Variable is block-scoped
document.write("ticket = " + ticket); // Outputs: "ticket = 123"
}
// Attempt to access the ticket variable outside its block
document.write("ticket = " + ticket); // Shows an error: "ticket is not defined"
}In this example:
- The variable
ticketis declared inside theifcondition block and is only accessible within that block. Accessing it outside results in an error becauselethas block-level scope.
No Shadowing and Hoisting:
letdoes not support shadowing or hoisting in the same way asvar. Each block can have its ownletvariable, but variables declared withletare not accessible before their declaration.
Example:
{
let ticket = 123; // Variable for this block
document.write("ticket = " + ticket); // Outputs: "ticket = 123"
}
{
let ticket = 456; // Different variable for this new block
document.write("ticket = " + ticket); // Outputs: "ticket = 456"
}In this example:
- Each
letvariable namedticketis independent of the others, existing only within its respective block. This prevents shadowing and ensures that variables do not interfere with each other across different blocks.
3. const
Variables declared with the const keyword also have block-level scope. They only allow initialization and once a variable declared with const is assigned a value, that value cannot be changed.
Example of const:
const userName = "The Coding Co."; // Variable declared with const
document.write("userName = " + userName); // Outputs: "userName = The Coding Co."
// Attempt to change the value of the constant variable
userName = "The Coders";
document.write("userName = " + userName); // Throws an error: "Uncaught TypeError: Assignment to constant variable."In this example:
- The variable
userNameis declared withconstand initialized with the value"The Coding Co.". Trying to reassign it to"The Coders"results in an error becauseconstvariables cannot be reassigned.
Block-Level Scope Example:
function show() {
if (true) {
const id = 123; // Variable declared with const inside a block
document.write("id = " + id); // Outputs: "id = 123"
}
// Attempt to access the id variable outside its block
document.write("id = " + id); // Throws an error: "Uncaught ReferenceError: id is not defined"
}In this example:
- The variable
idis declared withconstinside anifcondition block and is only accessible within that block. Accessing it outside the block results in an error.
No Shadowing and Hoisting:
constdoes not allow shadowing or hoisting in the same way asvarorlet. Variables declared withconstare not accessible before their declaration and cannot be shadowed within the same scope.
When to use const:
- Use
constwhen you want to ensure that a variable's value remains fixed and does not change.



