I'm back again. I had this little question about a possibility that I could declare a variable in the IF condition from a function, and to use it inside the statement itself.
Ok so, I'm curious to see if there's a way to declare a variable inside an IF statement's condition, and use that further along the statement as follows:
function SomeFunc() {return true}
if (let n = SomeFunc()) {
console.log(n); // true
// n is truthy
} else {
// Would never run, because it always returns true.
// This is just an example though, where it can return a truthy or falsy value dependent on the input context I could give it.
console.log(n); // false (if it actually returned 'false')
// n is falsy
}
Is there any way to do this, without having to run the function twice and not have it run outside the IF statement?
(Not like this though):
let n = SomeFunc();
if (n) { ... } else { ... }
// Or this:
if (SomeFunc()) {
let n = SomeFunc();
} else { ... }
I'd like to have one function being declared inside the condition, to minimalise line usage and have it - for me - clean. I hope there's a way to declare a variable inside of an IF condition.
Thank you in advance. ~Q
Aucun commentaire:
Enregistrer un commentaire