JavaScript Const
Understanding constant variables in JavaScript
🔒 What is const?
The
const
keyword creates variables that cannot be reassigned. Once you set a value, it stays the same throughout your program.
// Creating a constant variable
const myName = "John";
console.log(myName); // Output: John
Key Features of const
Cannot Reassign
Value cannot be changed after creation
const age = 25;
// age = 30; // Error!
Must Initialize
Must give a value when declaring
const name = "Alice"; // ✓ Good
// const city; // ✗ Error!
Block Scoped
Only exists within its block
if (true) {
const message = "Hi";
}
// console.log(message); // Error!
Objects Can Change
Object contents can be modified
const person = {name: "Bob"};
person.name = "Charlie"; // ✓ OK
🔹 Basic const Examples
Here are simple examples of using const:
// Numbers
const price = 19.99;
const quantity = 5;
// Strings
const productName = "JavaScript Book";
const category = "Education";
// Boolean
const isAvailable = true;
// Display the values
console.log("Product:", productName);
console.log("Price: $" + price);
console.log("In stock:", isAvailable);
Console Output:
Product: JavaScript Book
Price: $19.99
In stock: true
Price: $19.99
In stock: true
🔹 const vs let vs var
Understanding the differences:
// const - cannot reassign
const PI = 3.14159;
// PI = 3.14; // Error!
// let - can reassign
let score = 100;
score = 150; // OK
// var - old way (avoid using)
var oldVariable = "old style";
oldVariable = "changed"; // OK but not recommended
When to use const:
- Fixed values: PI, tax rates, API URLs
- Objects/Arrays: When the container won't change
- Functions: Function declarations
- Default choice: Use const unless you need to reassign
🔹 const with Objects and Arrays
const prevents reassignment, but object contents can change:
// const with objects
const student = {
name: "Emma",
grade: "A",
age: 20
};
// This works - changing object properties
student.age = 21;
student.grade = "A+";
console.log(student.name + " is " + student.age + " years old");
// const with arrays
const colors = ["red", "green", "blue"];
// This works - changing array contents
colors.push("yellow");
colors[0] = "orange";
console.log("Colors:", colors.join(", "));
Console Output:
Emma is 21 years old
Colors: orange, green, blue, yellow
Colors: orange, green, blue, yellow
🔹 Common const Mistakes
Avoid these common errors:
// ❌ Wrong - trying to reassign const
const username = "john123";
// username = "jane456"; // TypeError!
// ❌ Wrong - declaring without value
// const email; // SyntaxError!
// ❌ Wrong - trying to reassign array/object
const fruits = ["apple", "banana"];
// fruits = ["orange"]; // TypeError!
// ✅ Correct - modifying array contents
fruits.push("orange"); // This works!
console.log(fruits); // ["apple", "banana", "orange"]