5

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.

  • MDN explained the `delete` operator in its [website](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete). Variable is unable to use `delete` operator to remove it. Assign it with `undefined` instead. – Raptor Sep 29 '16 at 09: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; – Mohan Raj Sep 29 '16 at 09:14

2 Answers2

13

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

You can explicitly set the variable to undefined:

nxt = undefined;

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81