Search code examples
javascriptif-statementconditional-operator

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


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.


Solution

  • 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;