67

I was reading the documentation for https://github.com/rvagg/bl and I noticed that, in the examples, they use const to require a module and this made me wonder: is this a good practice? I mean, to me, this looked as a good idea.

A direct example from the link above is:

const BufferList = require('bl')

var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
/*...*/

I also noticed the lack the semicolons in the example but well, that has been discussed elsewhere thoroughly.

Community
  • 1
  • 1
Hugo
  • 5,484
  • 7
  • 35
  • 43
  • there's nothing wrong with it. I would guess it increases performance by ever so slightly as well – markasoftware May 06 '14 at 00:12
  • @Markasoftware This was the first time that I noticed that someone was using it and just makes sense, I mean, I don't it is wrong, but probably there is a reason behind the why is not that spread. – Hugo May 06 '14 at 00:22
  • 2
    @Hugo The reason why it is not that spread is that `const` has only been formalized recently in the ES6 standard. While some Browsers and serverside JS implementations provided `const` long before the ES6 standard, the semantics were different (in some browsers you could still reassign a new value to a const'ed variable). – helpermethod Jan 23 '15 at 11:00
  • @Markasoftware const actually decreases performance in most cases I know of. https://jsperf.com/const-vs-var – Florian Wendelborn Oct 21 '15 at 12:08
  • @Dodekeract wow, plot twist! I wonder why that is – markasoftware Oct 22 '15 at 02:18

1 Answers1

50

The const makes perfect sense here:

  • It documents that the object reference is not going to change.
  • It has block scope (same as let) which also makes sense.

Other than that it comes down to personal preference (using var, let or const)

Amol M Kulkarni
  • 19,000
  • 32
  • 110
  • 158
helpermethod
  • 51,037
  • 60
  • 165
  • 263
  • 14
    Note that `const` might lead to [worse performance](https://jsperf.com/const-vs-var). – Florian Wendelborn Oct 21 '15 at 12:03
  • 3
    If I make the hello array a var, I get 1% faster performance in the const section. I believe it may be due to the fact that world() pushes elements into the hello array, and thus, const needs to allocate new memory that was previously meant to be static. – Jon Jan 11 '16 at 22:04
  • @Jon: I think that should not make any difference. Because, the pointer that the `cont` obj is using cannot change in memory (reference), but the thing referenced or the memory pointer points to might change. (as in your example of array/ non primitive data type case only) – Amol M Kulkarni May 20 '16 at 10:13
  • 11
    @Dodekeract When I run your performance test in Chrome, `const` is actually faster than `var`. It must have changed over the last 3 years or so. – Ray Cheng Mar 01 '18 at 22:17
  • 3
    @Dodekeract @RayCheng I also get ~20% faster const with `Testing in Chrome 78.0.3904 / Windows 10 0.0.0`. – Det Nov 08 '19 at 20:39