How to check for boolean variables in Lightning Components? - El Toro - Find articles about Visualforce, Apex, Force.com and Salesforce in general

Print Preview

How to check for boolean variables in Lightning Components?

Three possible values for Boolean variables: True, False, Undefined.

Boolean variables can have three possible variables: true, false and undefined. To make it even more confusing, if you check for the value of an undefined variable in JavaScript, it returns false. But False, is not undefined! So how do you check for the value?

({
    buttonClick : function(component, event, helper) {
        var myBool = component.get("v.myBool");
        if (myBool == undefined) {
            alert("myBool was undefined");
        } else if (myBool) {
            alert("myBool was true");            
        } else if (!myBool) {
            alert("myBool was false");            
        }
    }
})

The check for undefined has to be done first, then check for true and false!

If you check backwards it will never work! Let me show you with a full example...

<aura:application >
    Undefined <c:Demo04a  />
    <hr/>
    True <c:Demo04a myBool="true" />
    <hr/>
    False <c:Demo04a myBool="false" />
</aura:application>

<aura:component >
    <aura:attribute name="myBool" type="Boolean" />
    <lightning:button label="Wrong" onclick="{!c.buttonWrong}" />
    <lightning:button label="Correct" onclick="{!c.buttonCorrect}" />
</aura:component>

({
    buttonWrong : function(component, event, helper) {
        var myBool = component.get("v.myBool");
        if (myBool) {
            alert("myBool was true");            
        } else if (!myBool) {
            alert("myBool was false");            
        } else if (myBool == undefined) {
            alert("myBool was undefined");
        }
    },
    buttonCorrect : function(component, event, helper) {
        var myBool = component.get("v.myBool");
        if (myBool == undefined) {
            alert("myBool was undefined");
        } else if (myBool) {
            alert("myBool was true");            
        } else if (!myBool) {
            alert("myBool was false");            
        }
    }
})

comments powered by Disqus

© El Toro . IT @ 2013
Andrés Pérez