Why Global Variable is not working inside of function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why Global Variable is not working inside of function?

https://code.sololearn.com/WM01Z72Slc1B/?ref=app

1st Jun 2021, 5:07 PM
Sajid Ali
Sajid Ali - avatar
6 Answers
+ 2
another (even better) way to proceed would be to avoid using event attributes in html source code, and rather define them at JS runtime: this avoid the needs of having function handlers exposed at global scope, and is more clean ;P there are two ways to do so: 1) assigning the on{event} attribute of the targeted element by assigning it the function you want to use (could be overrided) 2) use addEventListener method of the targeted element (cumulative, don't override previously setted function handlers)
1st Jun 2021, 7:59 PM
visph
visph - avatar
+ 3
Strenger Because you have written function inside window.onload so if you call that function from an element then it will give error and show function is undefined. So write function outside window.onload if you are calling from an element. https://code.sololearn.com/WduzulZIaaSN/?ref=app
1st Jun 2021, 5:57 PM
A͢J
A͢J - avatar
+ 2
Strenger Without null will also work but I have initialised with null. I just supposed that there in no value in page1 so I have just initialised with null.
1st Jun 2021, 6:30 PM
A͢J
A͢J - avatar
+ 1
better practice to keep all that you can in a local scope... so, rather than initializing only in the scope of window.onload function handler, keep all your code inside it (and explicitly declare your variables, else they will be implicitly declared in global scope) and export (copy reference) of your needed function at global scope... global scope is the window object, so assigning property to it will explicitly let them accessible from outside ^^ also, if there's no local variable overriding the global scope property name, you could just refer to window implicitly: that's why I use window explicitly for copy function references, but I use it implicitly for most as its methods (such as onload) ;) https://code.sololearn.com/WA6zBllK4Kom/?ref=app
1st Jun 2021, 7:43 PM
visph
visph - avatar
0
🅰🅹 🅐🅝🅐🅝🅣 why you are using page = null ?!
1st Jun 2021, 6:19 PM
Sajid Ali
Sajid Ali - avatar
0
🅰🅹 🅐🅝🅐🅝🅣 its also working if i will remove var page1 = null; from top!
1st Jun 2021, 6:22 PM
Sajid Ali
Sajid Ali - avatar