1

I've made a function "ADD" which modifies the value of a variable :

function ADD(xs, n)
{
    var nom_variable = xs;
    var XS = eval(xs);

    nouvelle_valeur = eval(nom_variable + "=XS+n");
}

var x = 5 ;

ADD("x",5); // now x = 10

I would like that the first argument of the function ADD is x, not "x". Is this possible ?

I want my students to write algorithms in a way similar to natural language.

Thanks !

Daniel Corzo
  • 1,055
  • 2
  • 19
  • 32
  • 1
    No, what you are asking is not possible. If a value is supposed to be a string, it must be quoted as a string. – Pointy Jan 02 '17 at 21:37
  • @Pointy: nothing that can be done with Reflection? – Jongware Jan 02 '17 at 21:38
  • 1
    JavaScript is pass-by-value, not pass-by-reference, so that's not possible. In other words, `foo(x)` passes the value of the variable `x`, not a reference to variable `x`. If `x` has the value `42`, then `foo(x)` and `foo(42)` are indistinguishable inside the function. Personally I would structure the function completely differently. I'd make it accept all value as input and return the value. – Felix Kling Jan 02 '17 at 21:41
  • 1
    Related: [Determine original name of variable after its passed to a function](http://stackoverflow.com/q/3404057/218196) – Felix Kling Jan 02 '17 at 21:46
  • @RadLexus reflection?? in JavaScript? – Pointy Jan 02 '17 at 21:57
  • @Pointy: [yes](http://stackoverflow.com/q/13910962/2564301). Alas, it only works with methods, not with plain variables. And the called function never sees the `x`. – Jongware Jan 02 '17 at 22:05
  • Yea I'm not sure I'd call that "reflection", though if it makes you happy to do so that's fine by me :) – Pointy Jan 02 '17 at 22:15
  • Thanks for your answers ! – rognntudjuu Jan 03 '17 at 06:09

1 Answers1

0

You can't pass x as if it were a reference, but you could construct a functional reference (or Lens) although you are still not passing x but a variable that is a reference of x.

var x = 5;
var xRef = {
  get : function(){
    return x;
  },
  set : function(val){
    x = val;
  }
}

function add(ref, n){
  var oldVal = ref.get();
  ref.set(oldVal+n);
}

add(xRef, 5);
console.log(x);

It's definitely not pretty though.

MinusFour
  • 13,913
  • 3
  • 30
  • 39