user91579631 user91579631 - 9 months ago 65
Node.js Question

Difference between importing module as const and var in node.js

I am using a mqtt client for node.js

On this link, mqtt module is imported like this;

const mqtt = require('mqtt')
const client = mqtt.connect('mqtt://')

The way I do my module import is like this;

var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://')

What is the difference between the 2 ways, var and const? What if I do the import this way;

let mqtt = require('mqtt')
let client = mqtt.connect('mqtt://')

Does it matter? Which is the correct programming way?

I am using node.js v6

Answer Source

Regardless of whether you're using it for a require or not, const means the variable cannot be reassigned, while let allows it to be reassigned. Both let and const are block scoped, while var is function scoped. Generally, most folks using ES6-compatible things (which node v6 is mostly ES6 compatible) suggest to prefer const and let and never (or rarely) use var. This tends to provide the scoping behavior that most folks expect, especially if coming from another language.

In the case of your require statements, I can't think of a case where you'd ever want to reassign those variables, so const should be the preferred method.