Home > OS >  alternatives for multiple if else conditions to make it in single line - javascript
alternatives for multiple if else conditions to make it in single line - javascript

Time:10-11

In one function, i am checking couple of condition with multiple if else condition. I want to do with using ternary operator to make it single line. I am not able to configure it how to do that

if (!this.$route.params.prdKey) {
            this.prodData.prdKey = '';
        } else {
            this.prodData.prdKey = this.$route.params.prdKey;
        }
        if (!this.$route.params.version) {
            this.prodData.version = 1;
        } else {
            this.prodData.version = this.$route.params.version;
        }
        this.pageMode = this.$route.params.pageMode;
        this.getProductDetailsList();
        if (!this.isPrdAvailable) {
            this.getproductList();
        } else {
            this.loadMoreproducts();
        }

Any other approach is also ok for me. There are in other part where i am using this kind of if-else condition check multiple times. So, i can remove those as well.

CodePudding user response:

|| can be used to alternate between two possibilities - if the left-hand side is truthy, it'll evaluate to it, otherwise it'll evaluate to the right-hand side.

this.prodData.prdKey = this.$route.params.prdKey || '';
this.prodData.version = this.$route.params.version || 1;

CodePudding user response:

You could use two ternary expressions here:

this.prodData.prdKey = this.$route.params.prdKey ? this.$route.params.prdKey : '';
this.prodData.version = this.$route.params.version ? this.$route.params.version : 1;
  • Related