Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined = true; then back to undefined?

Some javascript tomfoolery:

If this works

undefined = true;

then how can you revert back to set undefined back to representing undefined?


Sure, the easy way is to store undefined in another variable before setting undefined to true. What other way can you restore undefined?

First thought to set it back was delete undefined;, didn't work.

like image 622
MikeM Avatar asked Apr 20 '11 04:04

MikeM


People also ask

Why is my code returning undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Does undefined return true?

undefined will give true .

Is undefined === undefined true?

undefined == undefined is true.

Is undefined === false?

Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.


1 Answers

Alex's answer is the safe and practical way to ensure undefined is really undefined.

But JS is super flexible, so for fun, if you wish to revert the global undefined, then you can reassign window.undefined from the safety of a new function scope:

(function () {            // Create a new scope
   var a;                 // "a" is undefined in this scope
   window.undefined = a;  // Set the global "undefined" to "a"
})()                      // Execute immediately

Taking this idea futher, you can reconfigure the above to become:

undefined = (function () {
   var a;                 // "a" is undefined
   return a;              // return "a"
})();

Or really, just this:

undefined = (function () {
    return;
})();

But in fact, you don't actually need to return anything:

undefined = function(){}();

Of course, then there's also the void operator ;-) doh!

undefined = void 0;
like image 187
David Tang Avatar answered Sep 26 '22 17:09

David Tang