Reputation: 211
Often, I define and call a function like this - particularly when we use flags:
function cat(doMeon, doCloseEyes)
{
if (doMeon) console.log("Meon...");
if (doCloseEyes) console.log("Hmm, I closed my eyes...");
}
...
// And then call, using flags. Names are temporary, only for readability
cat(doMeon=true, doCloseEyes=true);
Note that we could just do "cat(true, true)" but that kills the readability.
But the problem this introduces is that the two variables are now in global scope. And we shouldn't polluting the global scope. But we can't do this:
// Doesn't work...
cat(var doMeon=true, var doCloseEyes=true);
Is there an approach that one can use as best practice here? (Note: Defining these vars outside is not such a good idea.)
Upvotes: 3
Views: 210
Reputation: 173582
You could create two functions instead:
function catDoMeon()
{
console.log("Meon...");
}
function catDoCloseEyes()
{
console.log("Hmm, I closed my eyes...");
}
catDoMeon();
catDoCloseEyes();
Upvotes: 0
Reputation: 66663
One method to pass in arguments with readability would be to pass an object containing each argument as a named property:
i.e.
cat({
doMeon: true,
doCloseEyes: true
});
And inside the function, you can do:
function cat(_props) {
if (_props.doMeon) console.log("Meon...");
if (_props.doCloseEyes) console.log("Hmm, I closed my eyes...");
....
}
Upvotes: 2