Nik
Nik

Reputation: 171

javascript error on undefined variable

I am bit confused on why I am getting 'msg' is undefined error (alert(msg) line) in below code. if I have at least one incorrect address ( address: 0) then I would expect below code to set inValidUser =1 and also set msg variable and then break the the loop. However, I then get a javascript error " Error: 'msg' is undefined." Any ideas?

function test(userData) {
    var myArr = [];
    var i;
    for (i = 1; i <= 3; i++) {
        myArr.push(
            jQuery.ajax({
            type: "GET",
            url: "http:/c.html/" + i,
            });
        );
    }

    $.when.apply($, myArr).done(function() {
        var i = 0;
        var invalidUser = 0;
        var tableData = [];

        $.each(arguments, function (idx, args) {
            if (args[0].address === 0) {
                invalidUser = 1;
                var msg = "User Address " + userData[j].address + " not correct";
                return false;
            } else {
                tableData.push({
                    name: userData[i].firstname,
                    age: userData[i].age
                });
            }
            i++;
        });
        if (invalidUser `enter code here`=== 1) {    
            alert(msg);
        } else {
            addTableData(tableData);
        }
    }).fail (function (jqXHR, textStatus) {
        //oops..failed
    });   
}

Upvotes: 0

Views: 128

Answers (1)

EyasSH
EyasSH

Reputation: 3769

You have a scope error in your code. When you declare a variable with var, it will be bound to the closest function that the declaration statement appears in.

In this case, it means this:

    $.each(arguments, function (idx, args) {
    //                ^^^^^^^^             ^ this scope
        if (args[0].address === 0) {
            invalidUser = 1;
            var msg = "User Address " + userData[j].address + " not correct";
    //      ^^^ declares variable in new scope
            return false;
        } else {
            tableData.push({
                name: userData[i].firstname,
                age: userData[i].age
            });
        }
        i++;
    });

What you will want to do is make sure that msg is declared in a scope that both uses of msg have access to. That would be:

$.when.apply($, myArr).done(function() {
    var msg;
//  ^^^^^^^^
    var i = 0;
    var invalidUser = 0;
    var tableData = [];

here, in your case.

When you set msg, then, you would use a variable assignment expression, rather than a declaration:

    msg = "User Address " + userData[j].address + " not correct";

Upvotes: 2

Related Questions