Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is x not deleted in the below program?

Tags:

javascript

var x = 1;
var output = (function() {
    delete x;
    return x;
 })();
console.log(output);

Is "delete" statement restricted only to objects?

like image 925
Krishna Manoj Varanasi Avatar asked Dec 04 '22 19:12

Krishna Manoj Varanasi


1 Answers

delete can only be used to remove object properties; it can't undeclare a variable (see MDN about it).

If you need to use this functionality, assign x to window:

window.x = 1;

var output = (function() {
    delete window.x;
    return window.x;
})();

console.log(output);

Note: Generally, cluttering up the window object is bad practice and should be avoided if at all possible.

like image 167
BenM Avatar answered Dec 06 '22 10:12

BenM