One of the biggest problems with declaring variables with the var keyword is that you can overwrite variable declarations without an error. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
I want to know how this mistake of overwriting declarations with the var keyword a programmer can go into if the application is big (as the tutorial suggests) can lead to unintended results. I want an example on the bugs that can happen in such cases.
Thanks in advance
Challenge: Explore Differences Between the var and let Keywords
var camper = 'James';
var camper = 'David';
console.log(camper);
I don’t think takes much imagination to imagine:
var camper = 'James';
// ...
// 287 lines of other code
// ...
var camper = 'David';
console.log(camper);
The coder has forgotten that there already is a variable with that name and redeclared it and now s/he thinks that there are two variables but there is really one. This could cause an error - s/he changes the “second” one and doesn’t realize that the “first” one is also being changed.
There are different ways to prevent this - write small functions, pay attention to scope, etc. But another way is to use let and const instead of var.
Me, I don’t think I’ve every encountered a problem with var. But that is probably also because I never use var. And I write small functions and manage my scope.
It does, thanks. I had a problem understanding what is the big deal if we used the same variable, without accounting for the programmer’s intention to actually declare two separate entities.