Anonymous Anonymous - 1 month ago 5
Javascript Question

Global variable wont update in second variable

When I call

foo2
, the global variable
divFoo
wont update when I
console.log
it.

var foo = 0;
var divFoo = "<div id='"+foo+"'>"
var foo2 = function() {
foo++
}


I have seen other questions pertaining to this issue and I felt that those didn't fully answer why this happens.
divFoo
shows div id='0' when
foo
is counting up. How do I make divFoo count up with foo?

Answer

You need to update divFoo when you update foo. It doesn't listen for changes, it's static.

Like this:

var foo = 0;
var divFoo;
var foo2 = function() {
    foo++;
    divFoo = "<div id='"+foo+"'>";
}
Comments