Filling a matrix with values I would like to hear your recommendations on when to use JavaScript's const over let, especially when applied to mutable objects as demonstrated in the following comparative code samples:

Strict preference of let:

// Create 100 x 100 zero-filled matrix:
let matrix = new Array(100);
for (let i = 0, length = matrix.length; i &lt; length; ++i) {
  matrix[i] = new Array(100).fill(0);
}

// Fill matrix with values:
function fill(matrix, value) {
  for (let row of matrix) {
    row.fill(value);
  }
}


Strict preference of const:

// Create 100 x 100 zero-filled matrix:
const matrix = new Array(100),
      length = matrix.length;
for (let i = 0; i &lt; length; ++i) {
  matrix[i] = new Array(100).fill(0);
}

// Fill matrix with values:
function fill(matrix, value) {
  for (const row of matrix) {
    row.fill(value);
  }
}


In my opinion, the const semantics in JavaScript are too weak to help static code analysis or to allow for compiler optimizations. Where const is (mis-)used to signal immutability, I'd go with e.g. declaring ALL_CAPS identifiers instead.

Is my thinking flawed? When writing robust, maintainable code, which of the above samples would you prefer? Is there a middle ground?
In my opinion, the const semantics in JavaScript are too weak to help static code analysis or to allow for compiler optimizations. Where const is (mis-)used to signal immutability, I'd go with e.g. declaring ALL_CAPS identifiers instead.


All const does is assure you that the value assigned to it is the same value throughout the scope. If it was assigned an array, it will be the same array and not suddenly change to another array or a different value altogether.

Mutation of the value, however, is a different story. JavaScript has no concept of immutability.Object.freeze does exist, and primitives are immutable, but that's about it.

For your code, if you're aiming to avoid mutation of your arrays, temporary values, counters and all, swap your loop for array.map and create a range function. Create a range, map through it, fill it with values, repeat.



function range(n){
  return Array(n).fill(0);
}

function matrix(dim, value){
  return range(dim).map(v =&gt; range(dim).map(v =&gt; value));
}

console.log(matrix(10, 2));