Salesforce Certified Application Architect

Friday 6 October 2017

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");           
            }
        }
    }) 

No comments:

Post a Comment

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...