By itself, it's not clear how this code is supposed to be helpful. Maybe with more context it would be clear.
Consider these options:
1. The function foo
was never defined:
If foo
is not declared then:
if(foo) {}
is a reference error. It crashes.
2. Foo is defined, but it isn't a function
foo
can be anything, so if you have foo
that looks like this:
let foo = true
if(foo) {
foo()
}
It's an error because you're trying to call something that's not a function.
So what exactly is this piece of code trying to test for? It won't call the function if the name foo
is declared and equals some falsy value like 0
or undefined
, but in other cases it will crash. It looks like it is trying to protect you from errors, but it doesn't really unless there's some other context where the name is declared but may be undefined.
A common context where foo
would be guaranteed to be declared is inside a function where foo
is an argument. The code would make more sense in an example like:
someFunction(foo){
if(foo) {
foo()
}
}
Here you can expect foo
to exist, but you still need to trust that the caller passed a function. This would guard against a situation where the called does not pass in an argument. (i.e. calling someFunction()
)