0

Variables

Must I initialise a variable with "var"? I tested it and it also worked without the word "var"!?

6th Oct 2016, 8:11 AM
Stefan Zimmer
Stefan Zimmer - avatar
2 Respostas
0
Hi! There are several types of scope in JS. If you initialize a variable inside of the function without the "var" addition then it will be a global variable that can be used outside of the function. If you use the "var" version, then the variable will be only local to this function and will not be accessible from the outside. <script> function testVar() { var localVar = 1; globalVar = 2; } testVar(); document.write(typeof localVar); // undefined document.write(typeof globalVar); // number </script> Hope it helps.
6th Oct 2016, 1:21 PM
yugor
0
Var is not required but if you can get into the habit of doing it, you will find later challenges easier
18th Oct 2016, 5:43 PM
Theo Jackson
Theo Jackson - avatar