Global variable is not updated javascript
I have globe.js, demo1.html , demo2.html here im declared var a = 10; in the global and then i reassigned the value of variable a in the demo1 window.a = 20 then i have anchor tag click to redirect to demo2 now im checking the value of a here alert(a); still it shows the global variable value 10 but i have been reassigned in demo1 showing old value of global please help me to find out...
Rajkiran SwainPosted Jul 1, 2017, 12:58 AM
Manikandan MurugesanPosted Jun 30, 2017, 9:01 PM
Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.
You can override this behaviour by declaring it locally using
var, but if you don't usevar, then a variable name used in a function will be global if that variable has been declared globally.That's why it's considered best practice to always declare your variables explicitly with
var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.Sundaram SubramanianPosted Jun 30, 2017, 11:14 AM