Why shouldn't use var in JavaScript

Why shouldn't use var in JavaScript

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)

No alt text provided for this image

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



Ricardo Barros Becheli

Senior Scrum Consultant

2 年

The best explanation I've seen so far. Thank you!

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了