JavaScript: Problems of var

Functions or variables in JS can be declared using let, const, var.

let, const are block scoped while var is function scoped.

Variables declared using var can be accessed outside the function, whereas variables declared using let and const can only be accessed in the block where they are declared.

This is a big headache, as far as privacy of variables are concerned. Variables can be tweaked, changed, dropped from outside the function, which is not desirable. The variables can also interfere with other variables which brings me to next point.

Variables declared using var can be declared twice, using the same name. Yes, you heard it right. For ex, something like below is perfectly legit.

var firstName = “Rakesh”

var firstName = “Ram”

Another big headache with var is the way variables declared using var are accessed. Variables declared using var are hoisted at the top of scope. But keep in mind, only declaration are hoisted not values.

For ex.,

Use cases with var

I am a software engineer. I specialize in JavaScript, React.js, NodeJS, Docker and Kubernetes.