6

This is what I tried so far.

var nxt = 'I am next';

window.onscroll = function(){
    var scr = this.pageYOffset;

    if(scr > 400){
        console.log(nxt);
        delete(nxt); // unset here
        console.log(nxt); // expected undefined or null
    }
}

I used delete() expecting to remove the reference value inside the variable. Unluckily, it just remain the same. Can somebody give me a clue on how to achieve this kind of scenario?

Any help would be appreciated.

2
  • MDN explained the delete operator in its website. Variable is unable to use delete operator to remove it. Assign it with undefined instead. Commented Sep 29, 2016 at 9:09
  • 1
    you can use delete to unset, but your variable should not declare as var Example: window.onscroll = function(){ scr = this.pageYOffset; if(scr > 400){ console.log(nxt); delete nxt; // unset here console.log(nxt); // expected undefined or null } } It will work as expected. or you can set to undefined or null nxt = undefined; (or) nxt = null; Commented Sep 29, 2016 at 9:14

2 Answers 2

15

You can't undeclare a variable. You can set its value to undefined, however:

nxt = undefined;

You can remove a property from an object, usually, depending on how it was added to the object. If this code is at global scope, your nxt variable is also a property of the global object (which you can reference via window on browsers), but properties added that way cannot be removed. So you could add it differently by doing this instead of declaring it:

window.nxt = 'I am next';

and then you could completely remove it with delete:

delete window.nxt;

(Note that delete is not a function, it's an operator; you don't use () with it, though doing so is harmless.)

However, global variables are a Bad Thing™, so I would probably suggest wrapping all of this in a scoping function, keeping nxt a variable, and setting nxt to undefined.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. That's a global variable for a plugin but not for the whole dom. It's wrap with (function(){ /* code */ })(); correct me if I am doing it wrong. Thanks man. You're the best!
@user111111: Ah, perfect then, it's already scoped. Nice one.
var e = [1,2,3];e[2] = undefined;console.log(e); will be [1, 2, undefined]
delete e[2] will show you [1, 2, empty]
@VasiliiSuricov - Yes, both true. I'm not sure how they relate to the answer...?
4

You can explicitly set the variable to undefined:

nxt = undefined;

2 Comments

Thanks. You're answer is right but I am going to pick T.J's answer because he explained it well. (+ one)
var e = [1,2,3];e[2] = undefined;console.log(e); will be [1, 2, undefined]