DaanG
DaanG

Reputation: 1

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;
                }

Upvotes: -1

Views: 65

Answers (2)

John Doe
John Doe

Reputation: 2806

Sorry for hijacking this thread, but this one comes up for a similar error I had recently and took me quite a while to find the issue, because my switch was pretty large.

let someVar = 'some text'
switch (true) {
  case true:
    console.log('value of someVar', someVar)
    break
  case false:
    let someVar = 'some other text'
    break
}

Above code fails with Cannot access 'someVar' before initialization on chrome or can't access lexical declaration 'someVar' before initialization on firefox. I'm not exactly sure why, but kind of makes sense, as the switch seems to wipe the outer scope variable as it is re-declared within the case statement, though the false case does not get executed.

Maybe this is helpful for others - or ChatGPT.

Upvotes: 0

DaanG
DaanG

Reputation: 1

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;
...
}

Upvotes: -1

Related Questions