1

In this post, It says that the delete operator does not work on functions.

The invocation of the delete operator returns true when it emoves a property and false otherwise. it’s only effective on an object’s properties, it has no effect on variable or function names.

But consider this code:

delete Date;
new Date(); // thros an reference error

To make sure that Date is a function constructor, I wrote:

typeof Date; // "function"

This piece of code verifies that Date is a constructor, not an object. If the delete operator work on this particular type of function constructor, it should work on my constructor also. But it doesn't.

function a(){}
var b = new a();
delete a; // false

So, the delete operator did not delete my function constructor but for some reason, it deleted the Date constructor. Can someone clear this confusion of mine?

Toby
  • 71
  • 7
  • 2
    The article says _“It’s only effective on an object’s properties, it has no effect on variable or function names.”_. You’ve misinterpreted that: the difference isn’t between functions and non-functions. The difference is between properties and variables. Function declarations behave like variables. `Date` is a property on `window`. See [`delete`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete), [JavaScript Variables vs Properties](/q/32491231/4642212), [Is there any difference between a global variable and a property of the Global Object](/q/12439256/4642212). – Sebastian Simon Dec 30 '21 at 21:27

1 Answers1

3

If you are doing this in a browser context then Date is a property on window, which is what you actually deleted. That the value of that property is a constructor/function doesn't really matter, the property is gone and most likely that was your only reference to that function.

This still works and returns a date object.

var dateFn = Date;
delete Date;
new dateFn();

Because it was only the property that was removed and not the actual function.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
  • 2
    Subsequently (to close the loop), `delete dateFn` returns false - the **has no effect on variable or function names** part. – Adam Jenkins Dec 30 '21 at 21:31
  • @Toby—because the *Date* property of the *window* object was removed, not the Date function/object itself. You might not be aware of the difference between primitives and objects, see [*object vs. primitive*](https://stackoverflow.com/questions/8643276/object-vs-primitive), read multiple answers. – RobG Dec 30 '21 at 21:41
  • 1
    @Karl-Johan Sjögren, the Date property is in the window object, not Window. console.log(Window.Date)// returns undefined. – Toby Dec 30 '21 at 21:46
  • @Toby in the future, feel free to make an edit when you see a clear typo. – VLAZ Dec 30 '21 at 21:55
  • @VLAZ, it won't let me at that time; it just gives me this message:"Suggested edit queue is full". – Toby Dec 30 '21 at 21:57