Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript should I use const instead of var whenever possible?

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;

};
like image 200
Richard Sands Avatar asked Sep 24 '14 11:09

Richard Sands


People also ask

Should I use const or var JavaScript?

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.

Why should you use const instead of VAR to store the HTTP server in your application?

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.


1 Answers

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)

like image 56
fmsf Avatar answered Oct 17 '22 01:10

fmsf