I'm using Node.js.
After my "sum" function gets deleted, I would expect the typeof(sum) to return "undefined", but it doesn't.
// functions are data in Javascript
var sum = function ( a,b ) { return a + b; }
var add = sum;
delete sum;
console.log ( typeof sum ); // should return undefined
console.log ( typeof add ); // should return function
console.log ( add( 1,2 ) ); // should return 3
I would think it should return:
undefined
function
3
But instead it returns:
function
function
3
You shouldn't use the delete
operator on identifiers (in scope variables, functions - as sum
- or function arguments).
The purpose of the delete
operator is to delete object properties.
When you declare a variable a function declaration or function arguments, behind the scenes these identifiers are actually a properties that belongs to the environment record of the current scope where they were declared.
Those properties are explicitly defined internally as non-configurable, they can't be deleted. Moreover, the usage of the delete
operator has been so misunderstanded that on ES5 Strict Mode, its usage on identifiers has been completely disallowed, delete sum;
should throw a ReferenceError
.
Edit:
As @SLacks noted in the question comments, the delete
operator does work with identifiers from the Firebug's console, that's because the Firebug uses eval
to execute the code you input in the console, and the variable environment bindings of identifiers instantiated in code executed by eval
, are mutable, which means that they can be deleted, this was probably to allow the programmer to delete at runtime dynamically declared variables with eval, for example:
eval('var sum = function () {}');
typeof sum; // "function"
delete sum; // true
typeof sum; // "undefined"
You can see how this happens also on the console:
And that's probably what happened with the book you are reading, the author made his tests on a console based on eval
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With