Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Local variable name shadows variable in outer scope JS-0123 #151

Open
philipjonsen opened this issue Mar 12, 2023 · 0 comments
Open

Local variable name shadows variable in outer scope JS-0123 #151

philipjonsen opened this issue Mar 12, 2023 · 0 comments

Comments

@philipjonsen
Copy link

'connection' is already declared in the upper scope on line 11 column 21.
[repl.js]

12 const config = mergeConfig(loadConfig('./config.js'));
13 const services = await createServices(config);
14
15 return withConnection(services.db, (connection) => {

Two variables can have the same name if they're declared in different scopes.
In the example below, the parameter x is said to "shadow" the variable x declared above it. The outer x can no longer be accessed inside the sum function.

const x = 1
function add(x, y) {
return x + y
}

While shadowing does not cause any problems most of the time, it does make the code harder to read and understand. We highly recommend against shadowing.

const r = repl.start();
Object.assign(r.context, {


BAD PRACTICE:

const file = "data.txt"

function readFile(file) {
// The parameter file shadows the toplevel variable file.
if (fs.existsSync(file)) {
return fs.readFileSync(file)
}
return null
}

RECOMMENDED:

// Prefer variable names that are distinct and convey as much
// meaning as possible.
const dataFile = "data.txt"

function readFile(filePath) {
if (fs.existsSync(filePath)) {
return fs.readFileSync(filePath)
}
return null
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant