3

could someone explain to me why startDate and endDate are not in scope in callback passed to filter function.

var events = [],
 eventsDataSource = [],
 statusChstatusChanges = [],
 statusChangesDataSource = [];

 function filterData() {
    var startDate = $('#start-date').data("kendoDatePicker").value();
    var endDate = $('#end-date').data("kendoDatePicker").value();

    events = eventsDataSource.filter(function (item) {
        debugger;
    });
    statusChanges = statusChangesDataSource.filter(function (item) {
        debugger;
    });
}

when I changed code to what's below it worked. starDate and endDate are in scope. Is lexical scope of callbacks/inline function created differently that function declarations?

function filterData() {
    var startDate = $('#start-date').data("kendoDatePicker").value();
    var endDate = $('#end-date').data("kendoDatePicker").value();

    function dateIsBetweenStartAndEnd(item) {            
        return new Date(item.Date) >= new Date(startDate) && new Date(item.Date) <= new Date(endDate);
    }

    events = eventsDataSource.filter(dateIsBetweenStartAndEnd);
    statusChanges =   statusChangesDataSource.filter(dateIsBetweenStartAndEnd);
}
pawel.podsiadly
  • 171
  • 2
  • 13
  • Maybe, but it's just a guess, it's because you declare and assign `events`first (outside `filterData`), and later in `filterData` you declare `startDate` and `endDate`. It could be a problem with hoisting? Try to declare the `events` where you use it, inside the `filterData` function – Pimmol Mar 29 '16 at 12:37

1 Answers1

1

I see you have some debugger statements in there.

Perhaps you are using Chrome's dev-tools and when you hit the debugger you are not able to access startDate and endDate.

This is simply an optimization that the browser is doing because it's not seeing any access of those functions in your code.

A quick way to verify this is to put a console statement above your debugger statement:

console.log(startDate);
debugger; // now you will be able to access startDate

Your understanding of lexical scope is correct...you are just hitting a runtime browser optimization.

For more information, see this chrome issue report.

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115