Recently, a new approach to declare variables
has come up in JavaScript. The essence of the
approach is that instead of let
we use
const
everywhere, except the cases when
we know for sure that the value will be variable.
See an example:
const a = 1;
const b = 2;
const c = a + b;
console.log(c);
This approach is very popular and you can find it in various third party sources.
However, I am against this fashionable approach. The fact is that constants were invented to store values like the number Pi. That is, for those values that are predefined in your program. Declaring all variables as constants contradicts this idea.
In addition, the behavior of arrays and objects is not very logical - we declare them constants, while we can easily change their properties. What are these constants if they can be changed?
Often declaring objects as constants is used to prevent us from changing the data type - to write a primitive instead of an object. But if we need type control, which is not available by default in JavaScript, then it is better to use its superset TypeScript.
In general, you can use this approach, since
this is the fashion, but I am against it, and
further in the tutorial, variables will still
be declared through let
, as it was
intended by the authors of the language.
Rewrite the following code through the described approach:
let arr = [1, 2, 3, 4, 5];
let res = arr[1] + arr[2];
console.log(res);