0

here is some code referring to a form

$form.submit(function(e) {

        e.preventDefault();

        var fields = ['id', 'name', 'subject', 'theory', 'practical']; //?
        var record = {};

        for (var index in fields) {

            var field = fields[index];

            if (field == 'id' || field == 'theory' || field == 'practical')
                record[field] = parseInt( $('input#'+field).val() );

            else
                record[field] = $('input#'+field).val();

        }

/* Now at this position if i initialize a $.ajax method and inside that I create a for loop again like this

for (var field in record) {

                            if (field == 'id')
                                continue;

Is the field here same as the field above??

*/ }

1 Answers1

0

Is the field here same as the field above?

Yes, with var it is. It wouldn't be with let in ES2015, but it is with var, because var anywhere in the function has function scope and declarations are hoisted to the top of the function they're in.

If we add that loop, we get this:

$form.submit(function(e) {

    e.preventDefault();

    var fields = ['id', 'name', 'subject', 'theory', 'practical']; //?
    var record = {};

    for (var index in fields) {

        var field = fields[index];

        if (field == 'id' || field == 'theory' || field == 'practical')
            record[field] = parseInt($('input#' + field).val());

        else
            record[field] = $('input#' + field).val();

    }
    for (var field in record) {

        if (field == 'id')
            continue;
    }
});

which is processed exactly as though it were this:

$form.submit(function(e) {
    // All of the variables are declared before step-by-step code runs
    var fields;
    var record;
    var index;
    var field;

    e.preventDefault();

    fields = ['id', 'name', 'subject', 'theory', 'practical']; //?
    record = {};

    for (index in fields) {

        field = fields[index];

        if (field == 'id' || field == 'theory' || field == 'practical')
            record[field] = parseInt($('input#' + field).val());

        else
            record[field] = $('input#' + field).val();

    }
    for (field in record) {

        if (field == 'id')
            continue;
    }
});

That would not be true if you were using let. With let, variables are block-scoped and only partially hoisted.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875