user91579631 user91579631 - 29 days ago 12
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 https://blog.risingstack.com/getting-started-with-nodejs-and-mqtt/, mqtt module is imported like this;

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


The way I do my module import is like this;

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


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://broker.hivemq.com')


Does it matter? Which is the correct programming way?

I am using node.js v6

Answer

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.