Golo Roden Golo Roden - 6 months ago 19
Javascript Question

const vs let when calling require

As io.js now supports ES6 you are finally able to use the

const
and
let
keywords. Obviously,
let
is the successor of
var
, just with some super-powers.

But what about
const
? I know, of course, what "constant" means, but I was wondering when to use it (regarding best practices).

E.g., if I create a module that requires another module, I could write:

'use strict';

const util = require('util');

const foo = function () {
// Do something with util
};

module.exports = foo;


Basically I've replaced every occurence of
var
with
const
. Generally speaking, I think that this is okay, but if I follow this pattern, it leaves me with way more uses of
const
than
let
, as most variables aren't "variables" in a literal sense.

Is this good style? Should I rather go for
let
? When should I choose
const
over
let
?

Answer

const can be normally used when you don't want your program

  1. to assign anything to the variable

    "use strict";
    const a = 1;
    a = 2;
    

    will produce TypeError: Assignment to constant variable..

  2. to use the variable without explicitly initializing.

    "use strict";
    const a;
    

    will produce SyntaxError: Unexpected token ;

Simply put, I would say,

  • use const whenever you want some variables not to be modified

  • use let if you want the exact opposite of const

  • use var, if you want to be compatible with ES5 implementations or if you want module/function level scope.

Use let only when you need block level scoping, otherwise using let or var would not make any difference.