const function parameters

Note: this is a cross-post from https://discourse.wicg.io/t/js-const-function-parameters/1927

let creates a mutable binding, and const creates an immutable binding. However function parameters are always implicity mutable, i.e.:

function foo(param) // 'param' is implicitly mutable
{
    console.log("param = " + param);
    param = 5;  // this is allowed
    console.log("param = " + param);
};

Why not allow const in function parameters?

function foo(const param) // 'param' is immutable
{
    console.log("param = " + param);
    param = 5;  // throws, cannot modify const parameter
    console.log("param = " + param);
};

In the second example using param would be treated the same as if it were defined as a local variable with const instead of let .

This would provide the same benefits as const for function parameters, i.e. readability, indicating intent, avoiding accidental modification of parameters, etc.

This would be extended to default parameters, e.g.

function foo(const param = 0)
{
    // ...
};

Perhaps for consistency let should then also be allowed to explicity indicate a mutable parameter? e.g.

function foo(let param)
{
    // ...
};

Do you foresee allowing function (var formalName) {...} as well?

Would you like this to extend to catch parameters?

Re allowing (let formalpattern) for consistency:

IIRC, let is allowed as a function parameter name since it was never a FutureReservedWord the way const was. (let => let)(typeof let)

But let let is not allowed. So we'd need to decide which is worse. Allow

let let = (let let) => let

or allow (let let) => ... as a formal parameter but not allow a declaration like let let;

1 Like