Home > front end >  Is it bad practice to have parameters the same name as a variable in the outer scope?
Is it bad practice to have parameters the same name as a variable in the outer scope?

Time:07-04

I've run into this enough that I thought I'd ask: is it bad to have parameters the same name as a variable in the outer scope. This happens alot when I write in React or Svelte where the state of the component is the name I want to use in the function. Below is some code I just wrote in Svelte where I run into this. I get that is works, but I don't really like it. I think it would also break if I needed to modify the function to use the state in the outer scope. Any pointers would be helpful. Thank you.

// global state named `files`
let files: File[] = [];

// also wanted to use `files` as a param name but couldn't
function handleFilesChange(uploadedFiles: File[]) {
    files = sortFilesChronologically(files, "desc");
}

// using `files` as a param name
function sortFilesChronologically(files: File[], direction: "asc" | "desc" = "asc") {
    return [...files].sort((file1, file2) => {
        const file1Time = new Date(file1.lastModified).getTime();
        const file2Time = new Date(file2.lastModified).getTime();
        const dirModifier = direction === "asc" ? 1 : -1;
        return dirModifier * (file1Time - file2Time);
    });
}

CodePudding user response:

It can potentially cause unnecessary confusion and errors, but tooling can help prevent this from happening at all or differentiate state from arguments. ESLint was already mentioned in that regard.

If a function does not rely on state reactivity, you can consider to extract it to a separate file where the shadowing would not happen.

Using prefixes like you did with handleFilesChange to separate the names is always an option as well. I often use new, old, current and the like.


I think it would also break if I needed to modify the function to use the state in the outer scope

You would just have to rename the function parameter first, which should be simple refactoring operation.

  • Related