If creating a reference to an object, and the reference is not going to change (even though the object will), is it better to use const instead of var?
For example:
const moment = require('moment')
exports.getQuotation = function(value) {
const quotation = {};
quotation.value = value;
quotation.expiryDate = moment().add(7, 'days');
// Do some other stuff with quotation perhaps
return quotation;
};
As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.
It makes code easier to read… If it's a const declaration we know that the value is not changed. We don't have to read the code to check whether the value is changed.
You can use const, but you have to run node on --harmony
node app.js --harmony
You also have to set "use strict"
, otherwise you'll have run-time execution issues:
exports.getQuotation = function(value) {
"use strict";
const I_AM_CONSTANT = {};
let quotation = {};
...
Other than that, yes if you are running node on --harmony
, semantically it makes more sense to use const
for constants. For actual variables you should use let
instead of var, as let
only defines the variable in the scope (avoids hoisting issues)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With