javascriptvariablesincrement

Why doesn't my variable's value change when a variable its value relies on also changes?


After hitting the increment button in my code below, y is equal to 7, but z stays equal to 7 instead of changing to 8.

Why don't JavaScript variables update within other variables? Is there a solution to this problem?

<body>
    <script>
        var y=6;
        var z=1+y;
    </script>
    <button onclick="y++">Increment</button>
    <button onclick="alert(y)">What is y?</button>
    <button onclick="alert(z)">What is z?</button>
</body>

Solution

  • The value held on variable z is calculated the moment you assign it to the variable:

    var z=1+y;
    

    If you want it to change, you have to update it manually:

    <button onclick="z=++y+1">Increment</button>
    

    Most computer languages behave like that, I believe.


    In JavaScript and other languages you can use "getters" and "setters" to achieve what you want, but the code will become more complex. Judge if you really think it's necessary:

    <body>
        <script>
        var vals = {
            _y : 0,
            z : 0,
            set y(val) {
                this._y = val;
            },
            get y() {
                this.z = this._y + 1
                return this._y;
            } 
        }
        vals.y = 6;
        vals.z = 1 + vals.y;
        </script>
        <button onclick="vals.y++">Increment</button>
        <button onclick="alert(vals.y)">What is y?</button>
        <button onclick="alert(vals.z)">What is z?</button>
    </body>

    https://jsbin.com/udediy/1/edit


    Another, simpler solution is to just use a function. That would work well for the example you gave:

    <body>
        <script>
        var y=6;
        var z = function() {
            return 1+y;
        }
        </script>
        <button onclick="y++">Increment</button>
        <button onclick="alert(y)">What is y?</button>
        <button onclick="alert(z())">What is z?</button>
    </body>

    https://jsbin.com/ojorax/1/edit