+ 1

Variable is initialized without document.getElementById()? | Question regarding JavaScript behavior

I just finished the JavaScript Course and played a little around with the simple Image Slider you create during the Course. I recognized that as long as the JavaScript variable has the same name as the Id of the html tag the variable is automatically initialized(?) and I can change the attributes of the html tag. Example: https://code.sololearn.com/WCYoDeOwhxtp/#js I comment out the slider variable. But the assignment of the new Image still works. Worked with Google Chrome and Microsoft Edge. Why does JavaScript behave like this? Edit 1: So, I read a little bit more about JavaScript and found out that if I don't write var before a varible it will be still declared as a global variable. Sadly don't explain why the variable has a value instead of undefined

20th Jan 2017, 11:09 AM
TrueAtraz
TrueAtraz - avatar
1 ответ
+ 1
There is a good answer: http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables In short: you should say thanks to Microsoft for this. Also don't use global scope for variables (variable defined with var not in function is also global, google "iife") and use dom selection functions like getById.
21st Jan 2017, 6:13 AM
Ivan G
Ivan G - avatar