Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to use const for all variables that will never be changed?

Given something like this:

const audio = React.findDOMNode(this.refs.audio);
const seeker = React.findDOMNode(this.refs.seeker);
const {left, right} = seeker.getBoundingClientRect();
const seekToPerc = (event.clientX - left) / (right - left);

audio.currentTime = this.props.totalRunTime * seekToPerc;

Is this overusing const? Should I be using let here?

like image 605
ffxsam Avatar asked Oct 23 '15 06:10

ffxsam


People also ask

Should you always use const?

Summary. 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.

When should you use const?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).

Why would you use a constant instead of a variable?

Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.

Can const variables be changed?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).


1 Answers

The use of const is up to the individual. Optimization of most javascript engines work best if you pretend that javascript is strongly typed. const would thus seem like a good idea.

Some facts.

  • MDN states that consts are block scoped like let. This is only true in strict mode.
  • Consts must be assigned a value on declaration. Only true in strict mode.
  • Consts can not be reassigned. This is true in both strict and normal but in normal javascript assigning to a constant fails silently which represents a source of hard to find bugs. (NOTE there is no good argument for not using strict mode)

The differences as an example

function log(d){console.log(d);}
(function (){
    if(true){
        const a = 10;  // correctly formed use of constant
        const b;       // does not fail
        log(a);        // 10;
        log(b);        // undefined
        b = 10;        // nothing happens. If you have forgoten this is a constant
                       // you will have a hard time knowing this assignment is failing
        log(b);        // undefined
    }
    // scope not respected
    log(a); // 10 const should have block scope. This does not seem to be true
            // in normal javascript
})();

// function in strict mode
// not this is an example only and can not run. It is a compilation of several functions
(function (){
    "use strict";
    if(true){
        const a = 10;    
        const b;     // SyntaxError: Unexpected token. Javascript parsing 
                     // stops here and the function will never be called
        a = 20;      // TypeError: Assignment to constant variable
    }
    // scope is respected
    log(a); // ReferenceError: a is not defined
})();

As you can see there is a big difference between using const in strict mode and not. It would be foolhardy to use constants in anything but strict mode.

Performance. Chrome was very early in its adoption of const, I have memory of using const at least 3 years ago. As I specialize in graphics, performance is critical. I reasoned that a const would provide a much needed performance advantage, much the same way #define does in C/C++ by simple code insertion of the constant value. Saddly by the end of that day I was completely turned against the use of const because of it terrible performance.

Since then it has improved.

jsperf "Consts V Vars"

Using const is consistently slower in all tests but it is marginal and too close to call. The only exception being block scope declaration where it was about 1/3rd the speed of var and let. One surprising finding is that let is now very fast on Chrome Beta, a month ago I would not go near it, this fact is the reason for my answer.

OP asked... Does it make sense to use const for all variables that will never be changed?

A year ago I would have said "NEVER USE IT". A few months ago I would have said, "Have a good reason but var is better".

Now my answer is most definitely use constants whenever you intend a variable to never change. Constants out performs literals and are as good as var.

const c = 10;
var v = 10;
var a = 10; // this is slower 
var a = c; // this is 20% faster
var a = v; // this is about < 1% faster than const.

At the rate of change browsers undergo, and from the performance changes in the last few months of both let and conston chrome. I would suspect that constants will out perform vars by the end of the year. (please note I am using Chrome Beta 47)

The tests I have performed do not provide much room for code optimisation, so I would guess there is additional performance in using const that is not evident in the tests.

A constant by its very nature is strongly typed, this gives the javascript optimisation algorithms something to use to provide additional performance.

Using constants makes for better code quality. Javascript (even strict mode) can hide a bug for a long time, using constants reduces the risk of bad assignments, accidental type conversion, and more.

BUT I place a big warning on the use of const. ONLY USE const in strict mode, its behaviour in normal javascript is dangerous and will only cause you problems.

like image 146
Blindman67 Avatar answered Sep 19 '22 23:09

Blindman67