Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a javascript var as undefined

Tags:

javascript

Given:

console.log(boo); this outputs undefined 

Given:

var boo = 1; console.log(boo); this outputs 1 

After defining boo and setting to 1, how can I then reset boo, so that console.log outputs undefined?

Thanks

like image 708
AnApprentice Avatar asked Apr 26 '11 20:04

AnApprentice


People also ask

Why is my VAR 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 .

How do you set a value to undefined in TypeScript?

Use the nullish coalescing operator (??) to set a default value if undefined in TypeScript, e.g. const result = country ?? 'Germany' . The nullish coalescing operator returns its right-hand side operand when the value to the left is undefined or null .


1 Answers

Solution

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!

Reference

This behavior is standard as far back as ECMAScript 1. The relevant specification states in part:

Syntax

return [no LineTerminator here] Expression ;

Semantics

A return statement causes a function to cease execution and return a value to the caller. If Expression is omitted, the return value is undefined.

To view the original specifications, refer to:

  • ECMAScript 5.1
  • JavaScript (Mozilla)

Appendix

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.

1. Assign undefined to boo

boo = 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.

2. Delete boo

delete 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.

like image 65
Gooseberry Avatar answered Sep 28 '22 04:09

Gooseberry