Search code examples
javascriptecmascript-6constants

How to make function parameter constant in JavaScript?


What I want to do is to use as many immutable variables as possible, thus reducing the number of moving parts in my code. I want to use "var" and "let" only when it's necessary.

This won't work:

function constParam(const a){
    alert('You want me to '+a+'!');
}

Any ideas?


Solution

  • Function parameters will stay mutable bindings (like var) in ES6, there's nothing you can do against that. Probably the best solution you get is to destructure the arguments object in a const initialisation:

    function hasConstantParameters(const a, const b, const c, …) { // not possible
        …
    }
    function hasConstantParameters() {
        const [a, b, c, …] = arguments;
        …
    }
    

    Notice that this function will have a different arity (.length), if you need that you'll have to declare some placeholder parameters.