javascriptreactjsscopeswitch-statement

Variables not accessible on switch


The variables start and end are not accessible inside of the other switch case. But should be.

The code



for (let key in filters) {
            let obj = filters[key];
            if (!filters.hasOwnProperty(key) || obj === '' || obj.length === 0) {
                continue;
            }
            let start;
            let end;
            switch (key) {
                case "datum_van": {
                    start = new Date(obj);
                    break;
                }
                case "datum_tot": {
                    end = new Date(obj);
                    break;
                }
                case "dateVal": {
                    filteredRoutes = filteredRoutes.filter(tocht => {
                        let date = this.parseJsonDate(tocht.datum_van);
                        switch (obj) {
                            case 0: return date >= start && date <= end;
                            case 1: return date >= start;
                            case 2: return date <= end;
                        }
                    });
                    break;
                }

Solution

  • I have found the issue, it is due to start and end not being accessible on the case "dateVal" fixed it by putting my let start; and let end; outside of the for loop.

    Like so:

    let start;
    let end;
    for (let key in filters) {
    ...
    }
    

    instead of:

    for (let key in filters) {
    let start;
    let end;
    ...
    }