Don’t let var be a const in your JavaScript code

var-let-const

June 2015, ES6 (or ES2015)- a new version of ECMAScript was released. Among the many additions and changes, were these 2 newly added keywords- let and const. let and const were introduced in JavaScript to make variables more readable and more predictable. 3 years down the line, today, we still see a lot of developers still using var (or not) to declare variables in their code. In this article, I’m going to explain which of these 3 should be used (or not) in which scenarios and why.

But before we get into the solution (of which one of these 3 to use when), let’s first quickly understand the problem – the reason let and const were introduced.

Let’s go back a few years (maybe a decade), somewhere between 2007-10, JavaScript is becoming popular with each passing day. Developers are using it more and more to add interactivity to their websites. It’s still being used for pretty basic stuff like animations, validation checks etc and is still limited to front-end of the websites. Developers like it, well, most of them. Some developers think JavaScript has issues and is missing features which are pretty common in most other languages. But it’s still not that big a deal since it’s just a scripting language helping add interactivity to the website and nothing more.

Fast forward a few years, Node.js comes into the picture, opening a whole new domain for Javascript. Developers are bombarded with front-end frameworks and libraries like AngularJs, Backbone.js, Ext JS, Knockout, React, Vue.js. And suddenly JavaScript (and it’s problems) comes to the fore. And this is where we come back to our original discussion (thanks for reading through). One of the bigger problems developers had with JavaScript was the way JavaScript handled scopes.

  • You’ve 2 scopes in JavaScript – global and local.
  • You do not necessarily need to declare a variable in JavaScript. If you initialize a variable without declaring, it’s basically considered global variable.
  • If you declare a variable (with var keyword) inside a function, it’s local to the function and any nested functions.
  • You can declare a variable after assigning a value to it.

So as you can see, we had a problem. And these problems (and many others) justified some developers not liking JavaScript. So, to solve these problems, ES6 introduced 2 new keywords – let and const, to help developers manage the variables better. So, let’s go through each one of these to understand which one to use in a given scenario.

VAR:
This is how developers have been declaring their variables traditionally. And even if you somehow forgot to declare, worry not, JavaScript will do it for you behind the scenes. Well, there’s just one small problem. If you don’t declare a variable yourself, JavaScript will declare it as a global variable and it becomes accessible throughout the window. Not to mention, it pollutes the global namespace.

var global = 'Global variable';
function test() {
    var local = 'Local variable';
    undeclared = 'Undeclared variable';
}
test();
console.log(global); // prints 'Global variable'
console.log(undeclared); // prints 'Undeclared variable'
console.log(local); // throws 'not defined' error

Another problem with var is Hoisting. In short, with JavaScript, you can declare a variable after it has been used. Sound crazy, right? Yeah, it is. So basically, when the javascript compiler goes through your code it moves all the variable declarations at the top within their scope, hence making it possible to assign a value to a variable before even declaring it. Well, I’m not a fan of this feature(?), let’s just leave it to that.

function test1() {
    var var1 = 'test';
    if (var1 === 'test') {
        var var2 = 'var2';
    }
    console.log(var1); // prints 'test' 
    console.log(var2); // prints 'var2'
    // logically should return undefined error 
    // since var2 is declared inside a if block
}
test1();

LET:
With let, you can declare a variable and not worry about JavaScript throwing it around.

  • with let, you cannot assign a value to a variable without declaring it.
  • variables declared with let will not be hoisted.
  • let supports block variables, meaning, you now have 3 scopes- global, local and block scope so a variable declared inside an if block remains inside the if block.
  • variables declared with let can be reassigned any number of times, similar to var.
function test2() {
    var var1 = 'test';
    if (var1 === 'test') {
        let var2 = 'var2';
    }
    console.log(var1); // prints 'test' 
    console.log(var2); // throws 'not defined' error
}
test2();

CONST:
This declaration, just like let, creates a variable whose scope can be either global or local to the block in which it is declared. The only difference is, variables declared with const cannot be reassigned. Although you can still modify a value inside a const.

const obj = {foo: 'lorem', bar: 'epsum'};
obj.foo = 'lorem lorem';

This is still valid.

So, which one to use? Well, I personally do not use var at all in my code. I think it makes the code more readable and makes sure JavsScript gives me no surprises at runtime. And I almost never get a scenario where let and const cannot do the job.

Also, as per the Airbnb style guide, which I follow, you should always begin a declaration with a const and if you think it’d be reassigned somewhere down the line make it a let. If you’re not sure whether or not it’ll be reassigned at the time of declaration, keep it a const and convert to let when needed. This will be a piece of cake if you have a good linting integration with your IDE or Code Editor. I recommend ESLint for Javascript and TSLint for Typescript linting.

Summary

  • Always start with const
  • Use let if reassignment is needed
  • Use a good linting integration in your code editor
  • Avoid using var

Subscribe to our Newsletter to get more such cool articles straight into your Mailbox,

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.