Use 'var' key to secure Local Variables in JavaScript
You might be wondering, if you have declared a variable inside any function, it is supposed to be a Local Variable.
Like in the example below:
function Fn() {
var LocalVar = 'With Var Keyword';
AlsoLocal = 'No Var Keyword';
console.log(LocalVar + ' / ' + AlsoLocal);
}
In the example above both variables is supposed to be Local. But that is wrong. Every time you forget to put the VAR keyword when declaring the variables, no matter the closure or contexts, that variables goes to be a Global variable.
Run these tests:
console.log(LocalVar); //This will give you error, because its a local one.
console.log(AlsoLocal); //This will run.
Pro tip: Make sure you use the keyword VAR when you want that variable to be a Local.
Updates
I meant to say Local/Global but ended up saying Private/Public. I have corrected those all.
Written by Shekhar Sharma
Related protips
2 Responses
This is more JavaScript 101 than a pro-tip, but worth pointing out I guess.
over 1 year ago
·
OMG! How can you can forget to use var? And what a language design allows this.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Variables
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#