Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
shal Avatar asked May 18 '15 23:05

shal


People also ask

How do you create a constant in JavaScript?

To create a constant, As first parameter, we are passing either window object or global object. As second parameter, we are passing name of the variable to be created, which is foo in this case. As third parameter, we are passing object to configure the variable behavior.

Can a parameter be constant?

Within function definition bodies, the parameters may be used like any other variable. But the parameters are constant in the sense that they can't be assigned to (i.e., can't appear on the left side of an assignment ( = ) statement)<. In other words, their value remains constant throughout the function body.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Are JavaScript function parameters mutable?

For some reason, the parameters in the object are already treated as members without assigning them to any member variables created in the constructor of the object. The parameters are mutable also as seen in the code block below.


1 Answers

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.

like image 152
Bergi Avatar answered Sep 17 '22 02:09

Bergi