Assignment to read-only global (e.g., undefined = 5)

Loading

Understanding “Assignment to Read-Only Global (e.g., undefined = 5)” in JavaScript


πŸ“Œ Introduction

In JavaScript, some global variables such as undefined, NaN, and Infinity are read-only, meaning they cannot be reassigned. Attempting to assign a new value to them, like undefined = 5, results in an error in strict mode or fails silently in non-strict mode.

In this detailed guide, we will explore:

  • What causes this error?
  • Why does JavaScript prevent reassignment of global constants?
  • How JavaScript handles these special values?
  • How to fix this error correctly?

1️⃣ What Causes This Error?

JavaScript has built-in global properties that have immutable values, meaning they cannot be modified. These include:

  • undefined
  • NaN (Not a Number)
  • Infinity

If you try to assign a new value to one of these properties, JavaScript either:

  1. Throws an error (in strict mode).
  2. Fails silently (in non-strict mode).

πŸ”Ή Example: Assigning a Value to undefined

undefined = 5;
console.log(undefined);  // Still remains undefined

βœ… Output (Non-Strict Mode):

undefined

πŸ”΄ Error (Strict Mode – use strict)

"use strict";
undefined = 5;  // TypeError: Assignment to constant variable.

πŸ”Ή Example: Assigning a Value to NaN

NaN = "Not a Number";
console.log(NaN);  // Still remains NaN

πŸ”΄ Error in Strict Mode

"use strict";
NaN = "Not a Number";  // TypeError: Assignment to constant variable.

2️⃣ Why Are Some Global Properties Read-Only?

JavaScript follows ECMAScript standards, where certain values must remain unchangeable to prevent unintended side effects in programs.

πŸ”Έ Reasons for Read-Only Global Variables

  1. Prevents accidental modifications
    • If developers could change undefined, it would break many JavaScript programs.
  2. Ensures consistency in code execution
    • undefined should always mean “not assigned”.
  3. Improves security and debugging
    • Allowing modifications could introduce hard-to-find bugs.

πŸ”Ή Example of a potential issue if undefined were mutable:

undefined = "Oops!";  // This would break many functions checking for undefined values
function checkUndefined(x) {
    return x === undefined;
}

console.log(checkUndefined());  // Should return true, but would break if undefined was reassigned

3️⃣ How JavaScript Prevents Reassignment

πŸ”Ή undefined, NaN, and Infinity are Non-Writable

console.log(Object.getOwnPropertyDescriptor(window, "undefined"));

βœ… Output:

{
  value: undefined,
  writable: false,
  enumerable: false,
  configurable: false
}

πŸ”Ή Key Takeaways:

  • writable: false β†’ Cannot be reassigned.
  • configurable: false β†’ Cannot be deleted or redefined.

4️⃣ Fixing the Error

βœ… Solution 1: Avoid Assigning Values to Read-Only Globals

Simply do not assign values to undefined, NaN, or Infinity.

"use strict";
undefined = 5;  // ❌ Wrong - This will throw an error

πŸ”Ή Instead, use a different variable:

let myUndefined = 5;  // βœ… Correct

βœ… Solution 2: Use let or const Instead of Reassigning Globals

Instead of modifying undefined, use a variable:

let myVar = undefined;  // βœ… Correct way
console.log(myVar);  // undefined

βœ… Solution 3: Check If a Variable is Undefined Correctly

Instead of relying on undefined directly, use:

if (typeof myVar === "undefined") {
    console.log("Variable is undefined");
}

πŸ”Ή Why?

  • Even if someone mistakenly defines undefined = 5, this check still works.

βœ… Solution 4: Use Object.getOwnPropertyDescriptor() to Verify Read-Only Properties

If you’re unsure whether a property is read-only, you can check its attributes:

console.log(Object.getOwnPropertyDescriptor(globalThis, "undefined"));

πŸ”Ή Output:

{
  value: undefined,
  writable: false,
  enumerable: false,
  configurable: false
}

Since writable: false, we cannot modify it.


5️⃣ Common Mistakes to Avoid

❌ Mistake 1: Using undefined in Comparisons Without typeof

if (someVar === undefined) {  // May break if `undefined` is reassigned
    console.log("Variable is undefined");
}

βœ… Fix:

if (typeof someVar === "undefined") { 
    console.log("Variable is undefined");
}

❌ Mistake 2: Trying to Modify NaN or Infinity

NaN = 100;  // ❌ Error in strict mode
Infinity = -1;  // ❌ Error in strict mode

βœ… Fix:

  • Use a separate variable instead of modifying them.

❌ Mistake 3: Expecting undefined to Be Mutable

undefined = "Changed";  
console.log(undefined);  // Still undefined

βœ… Fix: Do not assign values to undefined.


6️⃣ Summary & Best Practices

ConceptKey Takeaway
undefined, NaN, InfinityAre read-only global constants
Assigning new valuesFails silently in non-strict mode, throws an error in strict mode
Object.getOwnPropertyDescriptor()Helps check if a property is writable or configurable
Checking undefined valuesUse typeof myVar === "undefined" instead of direct comparison
Avoid modifying globalsUse let or const to store custom values

🎯 Final Takeaways

βœ… Never assign values to undefined, NaN, or Infinity.
βœ… Use typeof to check for undefined variables safely.
βœ… Use Object.getOwnPropertyDescriptor() to check property mutability.
βœ… Enable "use strict" to catch these errors early.

Would you like more examples on best practices?

Leave a Reply

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