DEV Community

Cover image for 3 Ways to declare variables in JavaScript: var, let, and const explained
Anshuman Bhardwaj
Anshuman Bhardwaj

Posted on • Updated on • Originally published at theanshuman.dev

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

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 sceptical 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" bla, bla.

tldr;

  • 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
  • can be re-declared in the same scope without throwing an error (even in strict mode)
  • can be re-assigned
  • 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
Enter fullscreen mode Exit fullscreen mode

because the interpreter sees this code like

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

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

  • it is block-scoped when defined inside one otherwise is globally scoped
  • cannot be re-declared
  • variables declared using let can be re-assigned but not const
  • 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);
Enter fullscreen mode Exit fullscreen mode

Conclusion

Every tool is build for serving some purpose, we should utilise for it's goodness and not just follow the herd criticising 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

Top comments (0)