Reputation: 333
I have the following code:
function() {
if (foo && foo.bar !== baz) { //needed because foo can be undefined, so foo.bar always returns value
function1()
return;
}
if (foo) {
function2()
} else {
function1()
}
}
I was wondering, what would be the best way to optimize these if statements, from code structure point of view.
Thanks for all the answers!
Upvotes: 1
Views: 85
Reputation: 74204
This can be converted into a one-liner:
foo && foo.baz === baz ? function2() : function1();
If foo
is falsey then it will execute function1
and if foo
is truthy but foo.baz !== baz
then it will still execute function1
. Otherwise, it will execute function2
.
The reason this works is because if foo
is truthy and foo.baz !== baz
is false
then function2
is only executed if foo.baz === baz
is true
.
Upvotes: 1
Reputation: 84673
An example could be:
if (!foo || foo.bar !== baz) {
function1();
} else {
function2();
}
Similar to kamituel's one, but shorter, and maybe easier to read.
Upvotes: 1
Reputation: 35950
Might be:
if ((foo && foo.bar !== baz) || !foo) {
function1();
} else {
function2();
}
Upvotes: 1