How to use if else conditions in Knockout JS Magento 2?

You can use knockout if-else conditions in Magento 2 with knockout way or Magento 2 approaches.

You have to use ifnot for the else conditions. else is not supported in knockout.

Knockout if and ifnot conditions same as if and else conditions in javascript.

Using Default Knockout JS
1. First Way

<!-- ko if: isDisplayed() -->
    <span class="price">100</span>
<!-- /ko -->
<!-- ko ifnot: isDisplayed() -->
    <span class="price">Guest User</span>
<!-- /ko -->

2. Second Way

<div data-bind="if: isDisplayed()">
    <span class="price">100</span>
</div>
<div data-bind="ifnot: isDisplayed()">
    <span class="price">Guest User</span>
</div>

If you have a function with a parameter,
<!– ko if: getCartParam(‘summary_count’) –>

Magento 2 Approach,
1. First Way

<if args="isDisplayed()">
    <span class="price">100</span>
</if>
<ifnot args="isDisplayed()">
    <span class="price">Guest User</span>
</ifnot>

2. Second Way,

<div if="isDisplayed()">
    <span class="price">100</span>
</div>
<div ifnot="isDisplayed()">
    <span class="price">Guest User</span>
</div>

If you have a function with parameters and want to write with Magento standard way,
<if args=”getCartParam(‘summary_count’)”>

Multiple If conditions:

<div if="isEnabled() && isDisplayed()">
    <span class="price">100</span>
</div>

You can apply multiple conditions statements in a single line with the above approach.