I've recently come across the const
keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):
const x = 'const'; const x = 'not-const'; // Will give an error: 'constant 'x' has already been defined'
I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var
keyword could be used to the same effect.
const
in place of var
?var
is used in place of const
or vice-versa?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.
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).
Costing is important to ensure that all expenses are covered and the group fixes a price that ensures a profit. The first and most important step is to identify ALL the costs of a business: production, sales, administrative, overheads, etc.
`const` is a signal that the identifier won't be reassigned. `let` is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.
There are two aspects to your questions: what are the technical aspects of using const
instead of var
and what are the human-related aspects of doing so.
The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.
The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var
should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const
. If under different circumstances the information should change, use var
to indicate that, even if the actual change doesn't appear in your code.
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