简体   繁体   中英

Does it cause a memory leak if you do not declare block scope inside a switch case? (ESLint no-case-declarations)

Take this code for example; it is a Redux reducer function:

export default (state = initialState, action) => {
    switch (action.type) {
        case EMPLOYEE_UPDATE: {                                           // <-- this {
            // action.payload === { prop: 'name', value: 'Jane' }
            const { prop, value } = action.payload
            return { ...state, [prop]: value }
        }                                                                 // <-- and this }

        default:
            return state
    }
}

I was simply trying to destructure action.payload to minimize duplication, and I noticed it was aggravating the ES Lint rule ( no-case-declarations ). Normally, I might turn it off after confirming the rule. This one seems much more serious due to this ES Lint definition:

...The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached.

Source: https://eslint.org/docs/rules/no-case-declarations

If I remember memory leak potential correctly, does this mean the compiler will maintain a reference to action.payload at all times? -- meaning that if a large loop, dataset or long running calculation got into there, it could cause massive memory consumption even though the case only executes when it matches because it cannot be garbage collected or ignored ?

First and foremost, is my interpretation correct?

The nature of my question is around what exactly { and } are protecting against in this execution context/lexical environment. Is it just memory leak potential or is there a topic I did not mention, as well?

The problem:

 switch (true) { case false: let x = 10; break; case true: let x = 20; //error there's already an x declaration in scope break; } 

The cases all share the same lexical scope. So the example runs an error.

So, a way to fix this is by adding a block statement to introduce block scope and localize the lexical declarations.

 switch (true) { case false: { let x = 10; break; } case true: { let x = 20; break; } } 

It's unrelated to memory issues. Other than initialized bindings inside the switch block (that should eventually be GC).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM