Why shouldn't use var in JavaScript
Israel Afonso de Carvalho Neto
Desenvolvedor de Softwares | Desenvolvedor Backend| NodeJS, SQL Server, JavaScript, TypeScript
The short answer is: Because of hoisting, because of scope, and because it can be reassigned.
So, what is hoisting?
according to MDN, JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope, before execution of the code.
It means every time we declare a variable with reserved word var the variable goes to the top in execution time.
console.log(age) // will show undefine
var age
age = 29
console.log(age) // will show 29
When this code was executed on the first line the variable age already exists in execution time because of the hoisting, but the variable has no value yet.
Scope and reassigning
The best explanation of the scope I have ever seen is this image of the site constletvar (and also it explain with more details about const let and var)
As you see the scope of var declarations is a bit confusing and can lead you into error. And the fact you can reassign a variable can turn your code into a huge headache.
doubt and suggestions? please contact me
Senior Scrum Consultant
2 年The best explanation I've seen so far. Thank you!