JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Const


📘 JavaScript constDeclaring Constants in JavaScript

The const keyword in JavaScript is used to declare block-scoped, read-only variables. Once a variable is declared with const, its value cannot be reassigned.


🔹 Syntax:
const pi = 3.14159;

🔹 Key Features of const:
  • 🟡 Must be initialized at declaration

  • 🟡 Cannot be reassigned

  • 🟡 Is block-scoped like let

  • 🟡 Does not allow redeclaration in the same scope


✅ Valid:
const name = "John";
❌ Invalid:
const age;         // ❌ Error: Missing initializer
const age = 30;
age = 35;          // ❌ Error: Assignment to constant variable

🔄 const With Objects and Arrays

const does not make objects/arrays immutable, but it prevents reassignment of the variable itself.

const person = { name: "Alice", age: 25 };
person.age = 30;          // ✅ Allowed
person = { name: "Bob" }; // ❌ Error

const nums = [1, 2, 3];
nums.push(4);             // ✅ Allowed
nums = [4, 5];            // ❌ Error

🔁 Difference Between let and const
Feature let const
Reassignment ✅ Allowed ❌ Not Allowed
Initialization Optional ✅ Required
Scope Block-scoped Block-scoped
Redeclaration ❌ Not allowed ❌ Not allowed


Practice Questions

Q1. How do you declare a constant variable named country with the value "India" using const?

Q2. How do you demonstrate that reassignment of a const variable causes an error?

Q3. How do you declare a constant object car and modify one of its properties (e.g., change color)?

Q4. How do you declare a constant array fruits with three elements and add a fourth element to it?

Q5. How do you show that redeclaring a const variable in the same scope causes an error?

Q6. How do you demonstrate that const is block-scoped using an if block?

Q7. How do you create a constant object user and log one of its properties (like user.name)?

Q8. How do you explain the difference between modifying an object vs. reassigning a const object? Show with code.

Q9. What happens if you declare a const variable without assigning a value? Show with code.

Q10. How do you write a const variable named MAX_SCORE with a numeric value and use it in a condition?


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top