45

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.

Ben
  • 1,525
  • 4
  • 17
  • 18
  • This is not working?!?! `var value_b = b; b = c;` ? – Cipi Mar 13 '11 at 20:31
  • Is this a general JavaScript question or is there anything jQuery-specific that hasn't been mentioned? – BoltClock Mar 13 '11 at 20:34
  • well its a general javascript/jquery/variable scope question i suppose – Ben Mar 13 '11 at 20:47
  • You can change the value of a parameter wherever you want, but the less confusing thing to do here would be to introduce a `var c;` into your outer function and then manipulate it from your inner functions. If I understand correctly, you explicitly don't want to do that. Why? –  Mar 13 '11 at 21:09

8 Answers8

51

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);
Teocci
  • 7,189
  • 1
  • 50
  • 48
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Of course when you pass an object you are in fact passing by reference. Primitives however are passed by value hence the issue. Encapsulate your primitive into an object and you should be set. – New Guy Mar 13 '11 at 21:23
  • 6
    @New Guy, that's not true. You're passing by value in either case, but for objects the value is a reference type. Here's a good SO answer that discusses it: http://stackoverflow.com/questions/518000/is-javascript-is-a-pass-by-reference-or-pass-by-value-language/5314911#5314911. Try to implement $(b).replaceWith(c) and then see that it doesn't work. –  Mar 20 '11 at 20:20
  • I was under the impression all varaibles in javascript are objects. How are prototype methods etc treated differently from code-created objects? – robisrob Mar 10 '17 at 17:22
  • @robisrob At first I thought that too, but think about it. When you perform functions on numbers, you are always using a static method of another object. For example, `Number.isInteger()`, not `Number.prototype.isInteger`. You CAN use the new keyword and the Number object, but I don't think many programmers would find a reason for this when they can just use the literal. – Marvin Feb 06 '19 at 02:56
26

You cannot change the value of an integer or a string in JavaScript BUT you can change the value of the attributes of an object for example

function change(x) {
  x.x = 2;
}

let y = { x: 1 };
console.log('Original:', y);

change(y); // will make y.x = 2;

console.log('Modified:',y);
Teocci
  • 7,189
  • 1
  • 50
  • 48
shadowcursor
  • 1,174
  • 1
  • 13
  • 19
  • Hey thank you! I was following a course which was built off another course and someone a function changed the original variable of an parameter and it was so confusing to me since it wasn't returned or assigned. – destroyer22719 Feb 01 '21 at 21:49
2

When passing an object, you are passing a reference to that object. So when modifying an object that was passed into a function you are modifying that original object. Therefore you can create a very simple object containing a single variable that will allow you to carry the value around from one function to the next.

There is one thing that should be noted about the way you are putting these function calls into the parameter list of another function. I am not certain what the order of execution is for evaluating a parameter list. Perhaps someone who knows more about Javascript can answer that. However, not all languages will evaluate a parameter list left to right which means you may find the second function executes before the first. Again though, I'm not certain of the order of execution for Javascript so that may not be a concern.

function(a,b){
    var object_c = {
        c: 10
    };

    $('selector').toggle(

    //send object_c in to gather a value and store it in the "c" field
    function(object_c){},

    //send the same object_c object into the second function
    function(object_c){}
)}
New Guy
  • 8,606
  • 1
  • 15
  • 12
1

If the variable is in the global scope, you can set it as follows:

function modify(name,newVal){
  window[name] = newVal;
}

Then, try this:

var foo = 10;
modify('foo','bar');
console.log(foo); // bar
Cyoce
  • 253
  • 3
  • 14
  • 4
    Note that `window` is used in web-browser JavaScript only, but other JavaScript environments have different equivalents. For example, `global` is the node.js equivalent. – John Militer Apr 05 '18 at 03:15
1

you can, but its bad practice,

Don’t Reassign Your Function Arguments

https://spin.atomicobject.com/2011/04/10/javascript-don-t-reassign-your-function-arguments/

use destructuring instead.

designy
  • 21
  • 3
0

You can replace the value:

function myFunc() {
    var a = 1, b = 2, c = 3;

    function changeB(a, b) {
        b = c;
    }

    changeB(a, b);    
}
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
Alistair Laing
  • 983
  • 1
  • 7
  • 18
-1
b = c; // very little is set in stone in javascript
davin
  • 44,863
  • 9
  • 78
  • 78
-2

Do You mean:

// fun is Your actual function (a,b)

var actualFunction = fun;

fun = function (a,b){
   var c = 10;
   actualFunction(a,c);
}

Let me explain what is going onhere: You are creating a variable (actualFunction) and let it hold pointer to Your function(a,b) (named here "fun"). Then You are setting new definition for "fun" so it's calling the old one with the parameters You like.

I'm not quite sure if it run without exceptions, but please try it and let us know.

Piotr Salaciak
  • 1,653
  • 1
  • 15
  • 28
  • fun is undefined in the first line, so actualFunction is also undefined... and your code should throw exception? – Cipi Mar 13 '11 at 20:33
  • My assumption was, that fun is the function that Ben was taking about. So it's not undefined. Try to execute this (it's working): function f1(){ alert('hello'); } function f2(){ alert('world'); } f1(); var holder = f1; f1 = f2; f1() – Piotr Salaciak Mar 13 '11 at 20:43