user3173427
user3173427

Reputation: 3

Change a variable value to use it in another variable

i'm starting in javascript and i've been in this struggle for many days, within me i think it's stupid and i'm close to solve it, but i can't see it, so I need your help. I want change a variable value with a onclick event and i can do it, but when i want use the new value in a operation inside another variable it doesn't work.

This is an example of what i want to do:

  <script type=text/javascript>
  a="";
  function setvalue(){
  a=1;
  return a;
  }

  x= "hola"+a;
  function show(){
  alert(x);
  }
  </script>

And in the html I have:

<input type="button" onclick="setvalue()" value="1" />
<input type="button" onclick="show()" value="2" />

When I use alert(a), it perfectly works but when a use x variable it doesn't works

Upvotes: 0

Views: 314

Answers (2)

Alberto Montellano
Alberto Montellano

Reputation: 6246

Yes, I agree with the comment : "You just get the value of a at that current moment that you build the string."

Additional notes about what is happening:

In Javascript, strings are inmutable. So, the first time you assign the value of 'a' to 'x', a copy of 'a' (the value in that moment) is assigned to 'x'. No matter if later 'a' changes, because you are not assigning 'a' as a reference.

If you want to assign by reference you should use an Object.

"Objects are passed around by reference. They are never copied."

Sample:

a={name:"cat"}; 
function setvalue(){
    a.name= "dog";
    return a.name;
}

x = a;
function show(){
    alert(x.name);
}

JSFiddle: http://jsfiddle.net/amontellano/xkZr8/1/

I hope it helps.

Upvotes: 0

Halcyon
Halcyon

Reputation: 57729

You're defining x too early. Define x in show with the current value of a.

var a = "";
function setvalue(){
    a = 1;
    return a;
}

function show(){
    var x = "hola" + a;
    alert(x);
}

Upvotes: 2

Related Questions