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?

Upvotes: 0

Views: 47

Answers (1)

AM Douglas
AM Douglas

Reputation: 1903

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+"'>";
}

Upvotes: 2

Related Questions