| Linking JavaScript (JS) to HTML | JavaScript Data Types | |
JavaScript Variables |
In this lesson, youβll learn:
var, let, and const.Variables are containers for storing data values in JavaScript.
The var keyword is the old way of declaring variables in JavaScript.
It is function-scoped, meaning it is accessible throughout the function in which it is declared.
Variables declared with var can be redeclared and updated.
They are also hoisted (moved to the top of their scope and initialized as undefined).
// Example with var
function testVar() {
if (true) {
var x = 10;
}
console.log(x); // 10 (accessible outside the block)
}
testVar();
var city = "London";
var city = "Paris"; // redeclaration allowed
console.log(city); // Paris
The let keyword was introduced in ES6 (2015).
It is block-scoped, meaning it is only accessible inside the block { } where it is declared.
Variables declared with let can be updated but not redeclared in the same scope.
They are also hoisted but remain in the Temporal Dead Zone until initialized.
// Example with let
function testLet() {
if (true) {
let y = 20;
console.log(y); // 20
}
// console.log(y); β Error: y is not defined (block-scoped)
}
testLet();
let score = 50;
score = 100; // β
allowed
// let score = 200; β Error: Cannot redeclare in same scope
console.log(score); // 100
const pi = 3.1416; // pi = 3.14; β Error: Assignment to constant variable
The const keyword (introduced in ES6, 2015) is used to declare variables whose bindings cannot be reassigned.
It is block-scoped (like let), meaning it only exists within the block { } where itβs declared.
A const variable must be initialized at the time of declaration.
While the variable identifier itself cannot be reassigned, if the value is an object or array, its contents can still be modified.
const PI = 3.1416; console.log(PI); // 3.1416 // PI = 3.14; β Error: Assignment to constant variable
const fruits = ["apple", "banana"];
fruits.push("cherry"); // β
allowed
console.log(fruits); // ["apple", "banana", "cherry"]
// fruits = ["mango"]; β Error: Cannot reassign the array
const user = { name: "Alice", age: 25 };
user.age = 26; // β
allowed
user.city = "London"; // β
allowed
console.log(user); // { name: "Alice", age: 26, city: "London" }
// user = { name: "Bob" }; β Error: Cannot reassign the object
for, if, class) cannot be used as names.| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Redeclaration | Allowed | Not allowed | Not allowed |
| Reassignment | Allowed | Allowed | Not allowed |
| Initialization | Optional | Optional | Required at declaration |
const by default.let only when the value will change.var in modern JavaScript.Create variables for your own profile (name, age, hobby, country).
Print them in the console in a formatted way. Try changing values using let and const.
| Linking JavaScript (JS) to HTML | JavaScript Data Types | |