0
Variables
Must I initialise a variable with "var"? I tested it and it also worked without the word "var"!?
2 Réponses
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.
0
Var is not required but if you can get into the habit of doing it, you will find later challenges easier