Pouissante
Pouissante

Reputation: 128

Vuejs check for a null or undefined value in a method

I don't understand why I can't do

openAndFillModalSoin(soin)
        {
            this.show = true,   

            this.vDate = soin.date,
            this.vCategorie = soin.categoriesoin.name,
            //This can be null
            if(soin.rabaisraion){
                this.vReasonReduction = soin.rabaisraison.id;
            }

            this.vPaiement = soin.moyendepaiement.nam,
            this.vRefer = soin.referedBy,
            //This can be null aswell
            this.vGiftCard = soin.boncadeau.id,
            this.vVoucher = soin.bonreduction.id;

            this.vID = soin.id;
        },

The "if" parts doesn't work, it asks for an expression.

If in method

Upvotes: 1

Views: 12290

Answers (3)

Vikram Biwal
Vikram Biwal

Reputation: 2826

//check undefined Array
if (typeof myArray === "undefined") {
    alert("myArray is undefined");
}

// check undefined object
if (typeof myObj === "undefined") {
    alert("myObj is undefined");
}

//check object property
if (typeof myObj.some_property === "undefined") {
    alert("some_property is undefined");
}

Upvotes: 0

Steven Spungin
Steven Spungin

Reputation: 29139

You have commas instead of semicolons ending the preceding line.

Upvotes: 2

Steven Spungin
Steven Spungin

Reputation: 29139

if(soin.rabaisraion){
                this.vReasonReduction = soin.rabaisraison.id;
            }

This this code will run when the following is NOT TRUE soin.rabaisraion is the number 0, false, null, undefined, or an empty string.

To reiterate, the string 'false', the string '0' and and an array (empty or not) are all true.

Also, if soin is null or undefined, that will be a runtime error.

Perhaps you want this:

if(soin && soin.rabaisraion){
   this.vReasonReduction = soin.rabaisraison.id;
}

Regardless, add a log before to see what's going on:

console.log('checking soin', soin)
console.log('checking boolean soin', !!soin)
if(soin && soin.rabaisraion){
   this.vReasonReduction = soin.rabaisraison.id;
}

The '!!' will force the value to boolean.

Upvotes: 1

Related Questions