Successfully added
JavaScript
by Patrik
Problem with var
There's a weakness that comes with var
. I'll use the example below to explain:
var greeter = "hey hi";
var times = 4;
if (times > 3) {
var greeter = "say Hello instead";
}
console.log(greeter) // "say Hello instead"
So, since times > 3
returns true, greeter
is redefined to "say Hello instead"
. While this is not a problem if you knowingly want greeter
to be redefined, it becomes a problem when you do not realize that a variable greeter
has already been defined before.
If you have used greeter
in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why let and const are necessary.
Referenced in:
Comments