I am using &&
like this and it works
typeof foo === 'function' && foo(); //if foo exist then call it
instead of
if (typeof foo === 'function') { foo(); }
Is it wrong to do or just a matter of style and taste? For me it is natural and I want to use &&
, but now a linter complained: Expected an assignment or function call and instead saw an expression.
Can there be any real issues here or is it just a matter of convention?
Here is a code snippet:
function foo(x) {
console.log("foo say " + x)
}
function bar(x) {
console.log("bar say " + x)
}
let s = "OK"
typeof foo === 'function' && foo(s)
if (typeof bar === 'function') bar(s)
/*
Function noo() does not exist.
Error to try call it is prevented by the check.
noo && noo() is not enough, so typeof is a must!
*/
typeof noo === 'function' && noo()
console.log("OK so far")
Notes
- To clarify my purpose was to use
&&
as a check for existence (declared and defined). - If the left hand side of
&&
fails the right hand side will not execute - It is useful in
return
and assignments too, butif
is not. If an else-part is wanted, then use?
. The then else parts has to return same type. - I missed
typeof
at first and have corrected but see in comments it miss. Maybe common mistake or just easy writing while we all show understanding. But to be correct (i think) - the only way to check existence is withtypeof
,instanceof
ortry
exceptwindow
things you can do for examplehistory && history.back()
. try { foo(); }; catch (e) {};
can be used. At least one catch clause, or a finally clause, must be present.if (a()) {b(); c()}
equalsa() && (b(), c())
because functions can be both in statements and expressions. Use comma operator.- The extreme is that the function is not declared and the other extreme is when function has already returned a value
x = x || foo()
it need not to return again (that is called memoization of a deterministic function)