'parameter is declared but its value is never read... why not
To send an email, I have a controller method as such:
const send = function (subject, template, to, options) {
// VSC says about "subject": is declared but its value is never read.
// VSC does not say this for the other three parameters.
return new Promise(function (resolve, reject) {
fs.readFile(template, "utf8", function (err, templateContent) {
if (err) {
return resolve(false);
}
var subject = subject;
console.log(subject);
// this is where I do read "subject" but it returns 'undefined'
// (even though I am passing the function a value for the parameter)
... etc
What am I doing wrong? In my mind, I have declared a parameter subject and I use later on in the controller method.
Solution 1:[1]
var subject = subject;
var subject creates a new variable, named subject in the scope of the callback function passed to readFile.
This shadows the subject variable created as a parameter name for the function assigned to send.
var subject = subject; therefore copies the value of the local subject (which is undefined at the time) to subject (which does nothing).
Give your variables different names even if they do similar things.
I recommend the use of a linter which can enforce a rule like no-shadow (you seem to be using one already — VS Code won't generate the error message, only report it from a tool which does — so make sure you turn that rule on for that tool).
Solution 2:[2]
var inside the function will be hoisted to the top so at runtime it is:
fs.readFile(template, "utf8", function (err, templateContent) {
var subject;
// ...
subject = subject; //undefined
});
Just use another name for your nested subject like _subject and avoid shadowing variable names in general.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
| Solution 2 | Code Spirit |
