Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  113] [ 7]  / answers: 1 / hits: 21739  / 8 Years ago, thu, september 29, 2016, 12:00:00

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.


More From » javascript

 Answers
21

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.


[#60558] Tuesday, September 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;