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
deleteoperator on identifiers (in scope variables, functions – assum– or function arguments).The purpose of the
deleteoperator 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
deleteoperator has been so misunderstanded that on ES5 Strict Mode, its usage on identifiers has been completely disallowed,delete sum;should throw aReferenceError.Edit:
As @SLacks noted in the question comments, the
deleteoperator does work with identifiers from the Firebug’s console, that’s because the Firebug usesevalto execute the code you input in the console, and the variable environment bindings of identifiers instantiated in code executed byeval, 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: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.