I have one function with two parameters, for example function (a,b)
. I want to within the function, take the value of b, and replace that with c. I was thinking of something like $(b).replaceWith(c)
, but it didn't work out. I know I can create a new variable within the function with the new value, but is it possible to change the value of b itself? Is something like this possible. Or are the parameters set in stone?
Let me try to explain what I am trying to do. There are three functions, one overarching function and then two functions within it which are triggered by toggle event. And I want the second function to do something to get a value and pass it on to the third function. So here would be the code
function(a,b){ $('selector').toggle( //I want this to gather a value and store it in a variable function(){}, //and I want this to accept the variable and value from the previous function function(){} )}
The only way I can think of doing this is to add a parameter c for the overarching function and then modify it with the first function and have the new value pass on to the second function.
Unlike many other languages, Java has no mechanism to change the value of an actual parameter.
You can assign that reference to another variable, and now both reference the same object. It's always pass by value (even when that value is a reference...). There's no way to alter the value held by a variable passed as a parameter, which would be possible if JavaScript supported passing by reference.
Modifying a parameter does not modify the corresponding argument passed by the function call. However, because arguments can be addresses or pointers, a function can use addresses to modify the values of variables defined in the calling function.
A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. Note the difference between parameters and arguments: Function parameters are the names listed in the function's definition.
You cannot pass explicitly by reference in JavaScript; however if b
were an object, and in your function you modified b
's property, the change will be reflected in the calling scope.
If you need to do this with primitives you need to return the new value:
function increaseB(b) { // Or in one line, return b + 1; var c = b + 1; return c; } var b = 3; console.log('Original:', b); b = increaseB(b); // 4 console.log('Modified:', b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With