Passing ECMAScript 6 const as an argument to a function

I read a lot about ES6 lately and decided to give it a try (using Babel ). I am a little confused by the new declarations of let and const variables.

I realized how different the area is from var ; and that const is a constant reference to the value (and not the value of the value itself!).

Q : What if I pass the variable const into a function call? Will the receive function be able to change the value / link? What for? Why not?

+4
source share
2 answers

The semantics of the parameter passed to the function is completely independent of how the parameter was declared (using var , let or const ). What is passed to the function is just some value. The receive function has no visibility of how and where the value was displayed, including, if it is a variable, how this variable is declared. He simply sees the meaning that has been conveyed. The new let and const keywords are not relevant to this behavior.

This is the source of some confusion that attaches value to an array or object that can manipulate this array or object. Therefore, I can do the following:

 const a = {}; ax = 1; 

const in the above example makes a itself a constant within its scope, so it cannot be re-declared or re-assigned, but it does not in any way prevent the internal structure of a from changing, in this case, adding the x property.

Similarly, in the context of parameter passing:

 function func(obj) { obj.x = 1; } const a = {}; func(a); 

Here func gets the value of a as obj , but with this value it can access / change the interiors of the object.

Possible interest: How to set a parameter constant in JavaScript? .

+4
source

As you can see here and here , so that const declares a constant with constants, read-only, not a named link.

Now, if you pass const to a function, you are actually creating a new scope:

You pass the constant "by value", and the local variable of the function will receive the value of the constant, not a reference to it, as in any immutable object (for example, in strings). You can change the local var, but not the original const.

+1
source

All Articles