Jump to content

Variables equal to another variable


buyerguy5
 Share

Recommended Posts

Hi, I am a novice at javascript and I am hoping the forum can help me out with a question:Given the following code:var x = 8;var y = x;var x = x+4;alert(y);The result is y=8Meaning, when you change the value of x (after the statement y=x), y doesn't correspond to x anymore.Is it possible to have y change with x all the time- is this doable?I thought in other languages, if you do y=x, it will permanently associate y with x so that every time x changes, so does y.How can this be done in javascript?Thanks

Link to comment
Share on other sites

You're assigning only the value of x to y. If x changes afterwards y is not affected. The one thing you can do is some kind of function reference.

var x = 8; var y = function() { return x; } x = x + 4; alert( y() );

People would call what you're asking for "syntactical sugar"

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...