Given:
console.log(boo); this outputs undefined
Given:
var boo = 1;
console.log(boo); this outputs 1
Aft
To reliably set a variable boo to undefined, use a function with an empty return expression:
boo = (function () { return; })();
After executing this line of code, typeof(boo) evaluates to 'undefined', regardless of whether or not the undefined global property has been set to another value. For example:
undefined = 'hello';
var boo = 1;
console.log(boo); // outputs '1'
boo = (function () { return; })();
console.log(boo); // outputs 'undefined'
console.log(undefined); // outputs 'hello'
EDIT But see also @Colin's simpler solution!
This behavior is standard as far back as ECMAScript 1. The relevant specification states in part:
Syntax
return[no LineTerminator here] Expression ;Semantics
A
returnstatement causes a function to cease execution and return a value to the caller. If Expression is omitted, the return value isundefined.
To view the original specifications, refer to:
For completeness, I have appended a brief summary of alternate approaches to this problem, along with objections to these approaches, based on the answers and comments given by other responders.
undefined to booboo = undefined; // not recommended
Although it is simpler to assign undefined to boo directly, undefined is not a reserved word and could be replaced by an arbitrary value, such as a number or string.
boodelete boo; // not recommended
Deleting boo removes the definition of boo entirely, rather than assigning it the value undefined, and even then only works if boo is a global property.