Declaring Variables in JavaScript

daniel13rady

Daniel Brady

Posted on January 20, 2020

Declaring Variables in JavaScript

The variable declarators available to us in JavaScript, and more specifically when to use them, are a hot topic of conversation these days. A few weeks ago, I read an article called "Another var vs let vs const":

Though the title made me smile, my response to the advice given was less positive:

I think we can summarise everythings in a few lines:

  • var: why? if you can avoid it, do it;
  • prefer const usage if possible of course (together with an immutable approach when updating objects)! But don't be scared using let, especially if the scope of your variables is small, for example inside a function.

To be clear, I think it is very nice summary of the reigning opinion I've been exposed to; but the gospel-like way in which it is given triggered a knee-jerk reaction of mine, which is to immediately question bold statements made without supporting arguments.

I realized I don't entirely agree, but I couldn't articulate why. So it got me thinking many hours of thoughts. And with deep thought comes opinions:

Immutable approach to state management? ✅
Prefer const? 🙅
Avoid var? 🙅
Embrace let? ✅

If you choose to follow my dive into this particular rabbit hole, I'd appreciate feedback!

The tools: a miniseries

I've written a miniseries of posts that encourages deep thoughts about variable declaration in JavaScript.

Clip from "I,Robot": 'Hold my pie'

📖 Most of the differences between our variable declaration tools pertain to (lexical) scope, so if you don't have a firm grasp of that subject, I highly recommend Kyle Simpson's short book Scope and Closures; it's a fantastic resource, and I think Kyle does a great job at explaining this area of language design in an easy-to-follow way.

GitHub logo getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.

Each post dives deeper into one of JavaScript's variable declarators, and rather than constitute a sequence they are intended to be standalone, interrelated references.

I have chosen to give them identical structures and also tried to keep the examples* as similar as possible for easily comparing and contrasting the information in each, should you choose (and I strongly encourage it 😄).

I hope they help you make better decisions about which one is the right tool for holding a particular bit of your data. 🙏 I've definitely learned a lot from trying to write them!



*For the curious, I'm using Carbon with some custom settings to generate pretty pictures from code.

💖 💪 🙅 🚩
daniel13rady
Daniel Brady

Posted on January 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Declaring Variables in JavaScript
javascript Declaring Variables in JavaScript

January 20, 2020