user1760110
user1760110

Reputation: 2336

Setting and getting global variable in JavaScript using jQuery

I am trying to work out why I am getting undefined data type on printName(). So how we can update a global variable trough a function (like a Setter) function and get access the updated value via other functions if needed.

$(function () {
    var name;

    function setName() {
        name = "TestName";
    }

    function printName() {
        alert(name);
    }
    printName();
});

Upvotes: 0

Views: 31

Answers (2)

XciA
XciA

Reputation: 338

$(function () {
    var name;

function setName() {
    name = "TestName";
}

function printName() {
    alert(name);
}
    setName();
    printName();
});

Upvotes: 1

T J
T J

Reputation: 43156

Because you haven't set the name using setName(). function. in other words you never called setName()

Upvotes: 1

Related Questions