var is long lost in the darkness of misunderstood principles.
The idea behind writing this article is to try and clear up the air around why new developers are sceptical about using
var and every time I ask this question in an interview all I get to hear is "var is bad", "var makes global variables" bla, bla.
varis function scoped, that is it'll only be accessible in the scope of the function it's declared in.
constare block-scoped, that is they'll only be accessible in the scope of the block they're declared in.
Those who are looking for a deeper explanation should continue reading.
var has been around since the beginning of time (just kidding, I think even before that). Some characteristics of a variable declared using
- it is function scoped when defined inside one otherwise is globally scoped
- can be re-declared in the same scope without throwing an error (even in strict mode)
- can be re-assigned
- can be used before the declaration line in code (although the value will be
console.log(test); // undefined var test = "512"; console.log(test); // 512
because the interpreter sees this code like
var test; // undefined is the default value console.log(test); // undefined test = "512" console.log(test); // 512
const and let
The behavior of
let is the same other than the fact that variables declared using
const cannot be re-assigned.
Some characteristics of variables declared using
- it is block-scoped when defined inside one otherwise is globally scoped
- cannot be re-declared
- variables declared using
letcan be re-assigned but not
- cannot be used before the declaration line in code (Reference error is thrown because variables are not a given default value)
console.log(test); // ReferenceError: Cannot access 'test' before initialization var test = "512"; console.log(test);
Every tool is build for serving some purpose, we should utilise for it's goodness and not just follow the herd criticising it.
I'll be writing another article explaining how we can best use these tools.
That's it for this one. I hope you find this article helpful! Should you have any feedback or questions, please feel free to put them in the comments below. For more such articles, please follow me on Twitter
Until next time
Did you find this article valuable?
Support Anshuman Bhardwaj by becoming a sponsor. Any amount is appreciated!