🧮 JavaScript Variables & Data Types
Estimated reading: 4 minutes 9 views

🔍 JavaScript Constants (const) – Detailed Syntax & Code Explanation


✅ Basic Syntax

const variableName = value;

🔎 Explanation:

  • const → This is the keyword that tells JavaScript you’re declaring a constant variable.
  • variableName → The name you give to the variable (must follow identifier rules).
  • = → The assignment operator.
  • value → The initial value to assign. This is mandatory with const.

🧠 You must assign a value when declaring a const. If you don’t, JavaScript throws a SyntaxError.


📌 Example 1: Declaring a Constant

const pi = 3.14159;
console.log(pi); // Output: 3.14159

🔎 Line-by-Line Explanation:

  • const pi = 3.14159;
    • Declares a constant named pi and assigns it the value 3.14159.
    • This value cannot be reassigned later in the code.
  • console.log(pi);
    • Prints the value of pi to the console.
    • ✅ Output will be 3.14159.

🔒 Block Scope with const

{
const greeting = "Hello";
console.log(greeting); // ✅ "Hello"
}
console.log(greeting); // ❌ ReferenceError

🔎 Line-by-Line Explanation:

  • { ... } → Defines a block scope.
  • const greeting = "Hello";
    • Declares a constant inside the block.
    • The variable greeting exists only within the block.
  • console.log(greeting);
    • Inside the block, so it prints Hello.
  • console.log(greeting); (outside block)
    • ❌ ReferenceError, because greeting is not accessible outside the block.

💡 Unlike var, const does not leak outside block scopes.


❌ Reassignment is Not Allowed

const color = "blue";
color = "red"; // ❌ TypeError

🔎 Explanation:

  • const color = "blue";
    • Declares a constant with value "blue".
  • color = "red";
    • ❌ You’re trying to reassign a new value to a const variable — this is not allowed.
    • Result: TypeError: Assignment to constant variable.

⚠️ Constants are immutable by reference, not by value for objects.


❌ Must Be Initialized

const age; // ❌ SyntaxError

🔎 Explanation:

  • This throws a SyntaxError because:
    • const variables must be initialized at the time of declaration.
    • No value was assigned here.

✅ Always provide an initial value when using const.


🧪 Mutating Arrays with const

const numbers = [1, 2, 3];
numbers.push(4); // ✅ Allowed
console.log(numbers); // [1, 2, 3, 4]

// numbers = [5, 6]; ❌ TypeError

🔎 Line-by-Line Explanation:

  • const numbers = [1, 2, 3];
    • Declares a constant array.
  • numbers.push(4);
    • ✅ Allowed! You’re modifying the contents inside the array.
  • console.log(numbers);
    • Outputs the updated array → [1, 2, 3, 4].
  • numbers = [5, 6];
    • ❌ Not allowed — you’re trying to reassign the array reference, which is illegal for a const.

📘 You can mutate the contents of arrays or objects, but you cannot reassign the reference.


🧪 Mutating Objects with const

const user = { name: "Alice" };
user.name = "Bob"; // ✅ Allowed
console.log(user.name); // Bob

// user = { name: "Charlie" }; ❌ TypeError

🔎 Line-by-Line Explanation:

  • const user = { name: "Alice" };
    • Declares a constant object with one property.
  • user.name = "Bob";
    • ✅ Allowed! You’re modifying a property within the object.
  • console.log(user.name);
    • Output will be "Bob".
  • user = { name: "Charlie" };
    • ❌ Reassigning a whole new object is not allowed with const.

💡 To fully freeze object values, use Object.freeze(user).


🧠 Advanced Usage Tip – Object.freeze()

const config = Object.freeze({ debug: true });
config.debug = false;
console.log(config.debug); // Still true

🔎 Explanation:

  • Object.freeze(...) makes the object immutable — you can’t change its properties.
  • Even though config.debug = false; is written, it will not change the value.
  • Output: true

📊 Code Behavior

Operationconst Behavior
Declaration without init❌ SyntaxError
Reassigning value❌ TypeError
Mutating array contents✅ Allowed
Mutating object properties✅ Allowed
Reassigning object/array❌ TypeError
Used inside block {}✅ Block scoped

✅ Summary

JavaScript’s const is perfect for declaring unchanging variables. It’s block-scoped, must be initialized immediately, and prevents reassignment — though it doesn’t make objects or arrays immutable by default.

📌 Remember: const gives clarity and stability to your code by making intent obvious — if something shouldn’t change, declare it as a constant!


❓ FAQ – JavaScript const

❓Can I change the value of a const array or object?

Yes, you can mutate (change contents of) arrays and objects declared with const, but you cannot reassign the variable itself.

❓Why use const over let?

Using const helps prevent bugs by making it clear which variables should never be reassigned. It’s also a good practice for improving code readability and maintainability.

❓Is const hoisted?

Yes, but it’s in the temporal dead zone (TDZ). You can’t access it before the declaration line.

❓What happens if I declare a const without initializing it?

You’ll get a SyntaxError. const declarations must be initialized.

❓Is const better than var?

In modern JavaScript, yes. const and let are block-scoped and safer to use. var can lead to unexpected bugs due to hoisting and scope behavior.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript Constants (const)

Or Copy Link

CONTENTS
Scroll to Top