3 ways to declare variables in JavaScript: var, let, and const explained

Anshuman Bhardwaj
JavaScript in Plain English
3 min readApr 11, 2022

--

At the time of writing this article, there are only two popular ways of declaring variables in JavaScript: let and const; poor var is long lost in the darkness of misunderstood principles.

The idea behind writing this article is to try and clear up the air around why new developers are skeptical about using var and every time I ask this question in an interview, all I get to hear is "var is bad", "var makes global variables", blah blah blah.

tl;dr

  • var is function scoped, that is it'll only be accessible in the scope of the function it's declared in.
  • let and const are block-scoped, that is they'll only be accessible in the scope of the block they're declared in.

Those who are looking for a deeper explanation should continue reading.

var

var has been around since the beginning of time (just kidding, I think even before that). Some characteristics of a variable declared using var:

  • It is function scoped when defined inside one otherwise is globally scoped.
  • It can be re-declared in the same scope without throwing an error (even in strict mode).
  • It can be re-assigned.
  • It can be used before the declaration line in code (although the value will be undefined).
console.log(test); // undefined

var test = "512";

console.log(test); // 512

Because the interpreter sees this code like:

var test; // undefined is the default value
console.log(test); // undefined
test = "512"
console.log(test); // 512

const and let

The behavior of const and let is the same other than the fact that variables declared using const cannot be re-assigned.

Some characteristics of variables declared using const and let:

  • They are block-scoped when defined inside one otherwise is globally scoped.
  • They cannot be re-declared.
  • Variables declared using let can be re-assigned but not const.
  • They cannot be used before the declaration line in code (Reference error is thrown because variables are not a given default value).
console.log(test); // ReferenceError: Cannot access 'test' before initialization

var test = "512";

console.log(test);

Conclusion

Every tool is built for serving some purpose, we should utilize for it’s goodness and not just follow the herd in criticizing it.

I’ll be writing another article explaining how we can best use these tools.

That’s it for this one. I hope you find this article helpful! Should you have any feedback or questions, please feel free to put them in the comments below. For more such articles, please follow me on Twitter.

Until next time!

Originally published at https://theanshuman.dev on April 11, 2022.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--