1

So often I see functions being assigned to variables in JavaScript like this:

var square = function(number) {
  return number * number;
}

Is there any benefit to using const instead if the variable will never be reassigned to another function or value? Is there any reason not to use const?

const square = function(number) {
  return number * number;
}
at.
  • 50,922
  • 104
  • 292
  • 461
  • const is a ES-6 notation. Not sure about the differences though. Would like to know more about this one. – Akshay Khandelwal Oct 31 '15 at 19:14
  • I can't speak for any performance benefits, but I definitely like to use `const` as a safeguard for any identifiers I know should not be reassigned. – Casey Foster Oct 31 '15 at 19:16
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Browser_compatibility – Fayyaz Naqvi Oct 31 '15 at 19:17
  • 1
    Is there any particular reason you feel its use would be any different with a function reference than a "normal" variable? – James Thorpe Oct 31 '15 at 19:17
  • Please note that just because an identifier has been `const`d does not mean the referenced object is immune to changes, e.g. you can set `square.foo = 'bar';` and it will work normally. If you also want to prevent this, use `Object.freeze(square)` too – Paul S. Oct 31 '15 at 19:20
  • Well I had something to add in regards to performance and quirks between strict mode and not. Think Ill add the answer to the unanswer duplicate. – Blindman67 Oct 31 '15 at 20:02
  • @at: I just did, but usually it doesn't matter much which question exactly is linked in the box. The comments (which were unfortunately auto-deleted) are often enough more helpful. – Bergi Oct 31 '15 at 21:55

0 Answers0