This content originally appeared on DEV Community and was authored by Anshuman Bhardwaj
At the time of writing this article there are only two popular ways of declaring variables in JavaScript: let
and const
, poor 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.
tldr;
-
var
is function scoped, that is it'll only be accessible in the scope of the function it's declared in. -
let
andconst
are 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
var
has been around since the beginning of time (just kidding, I think even before that). Some characteristics of a variable declared using var
- 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
undefined
)
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 const
and let
is the same other than the fact that variables declared using const
cannot be re-assigned.
Some characteristics of variables declared using const
and let
- it is block-scoped when defined inside one otherwise is globally scoped
- cannot be re-declared
- variables declared using
let
can be re-assigned but notconst
- 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);
Conclusion
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
This content originally appeared on DEV Community and was authored by Anshuman Bhardwaj
Anshuman Bhardwaj | Sciencx (2022-04-11T07:05:38+00:00) 3 Ways to declare variables in JavaScript: var, let, and const explained. Retrieved from https://www.scien.cx/2022/04/11/3-ways-to-declare-variables-in-javascript-var-let-and-const-explained/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.