4

I am importing library in my nodeJS code using const or var, want to know which is a better approach and memory efficient?

Option 1:

const _ = require('lodash');

Option 2:

var _ = require('lodash');

Which is better? Option-1 or Option-2 ?

Mrugesh Vaghela
  • 195
  • 1
  • 1
  • 11
  • Possible duplicate of [Const in javascript? When to use it and is it necessary](https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary) – 1565986223 May 02 '19 at 09:05
  • 1
    That is not the duplicate of it, as I wanted to know if ```const``` can be used in importing libraries or not. – Mrugesh Vaghela May 03 '19 at 10:33
  • Duplicate of [const vs let when calling require](https://stackoverflow.com/questions/28135485/const-vs-let-when-calling-require) and [What is the best way to require node modules var or const?](https://stackoverflow.com/questions/44212934/what-is-the-best-way-to-require-node-modules-var-or-const) – nvidot Oct 20 '21 at 14:13

1 Answers1

10

Using const makes the most sense here. You don't want to accidentally overwrite the library you have imported as that may lead to hard to detect bugs. Marking it as const will throw errors if you attempt to reassign to it (but doesn't make it immutable). Using const may also allow js interpreters (or compilers in most cases now) to perform additional optimisations.

James Coyle
  • 9,922
  • 1
  • 40
  • 48
  • is there any performance issue am I going to add when i use ```const``` ? – Mrugesh Vaghela May 03 '19 at 10:31
  • 1
    Not that I am aware of. Const should generally be faster as the engine can perform additional optimisations. Though unless you are defining millions of variables in your code the difference will be negligible anyway. Don't prematurely optimize your code as it's a massive time sink. – James Coyle May 03 '19 at 10:35
  • gotcha Thanks. Still i am not accepting your answer because I want to know which is better? If I am not getting any other answer, your answer will be accepted :) thanks. – Mrugesh Vaghela May 06 '19 at 06:34
  • 2
    It's purely subjective which is better. Use whichever makes sense. If the variable needs to change use `var` or `let`, if it doesn't use `const`. – James Coyle May 06 '19 at 09:06
  • 2
    Don't try to optimize code unless it actually needs it. You should _always_ favor readability and be explicit in your code. The difference between const and not const will be less than a millisecond if anything so will be completely insignificant. Focus your attention on recursive operations, deep call stacks, and loops (especially those with computationally heavy operations O(n^2) or greater). – James Coyle May 06 '19 at 09:13
  • Agreed, thanks @james Coyle. Accepting your answer now. Make sense. – Mrugesh Vaghela May 07 '19 at 06:08