I am just learning JavaScript, and I don't understand why the following code doesn't produce an error:
myTest = 5;
function addFifteen(num) {
return num+15;
}
document.write(addFifteen(myTest));
Why do I not need "var" before "myTest"? If it runs without "var", what is the purpose of writing that?
When you do not specify a var
before the variable, it is still valid javascript. This is why it does not produce an error. However, as a best practice, you should avoid this, because variables thus declared get tagged to the global scope window
.
Having too many variables / functions thus declared is said to "pollute" your global scope and isn't considered good programming practice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.