Example

Truthy and Falsy

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
    <title>Truthy and Falsy </title>
</head>
<body>
<!--
    All JavaScript values have an inherent truthyness or falsyness about them.
    Falsy values listed below, rest all are truthy:
        - false
        - null
        - "" (empty string)
        - 0
        - undefined
        - NaN
-->
    
    <h1>Demo: Truthy and Falsy values</h1>

    <div>
        <h2>When the string is empty, it has falsy value</h2>
        <p id="para1"></p>
    </div>

    <div>
        <h2>When the variable is undefined, it has falsy value</h2>
        <p id="para2"></p>
    </div>

    <div>
        <h2>0 (zero) will be false, hence '!0' is 1 i.e true value</h2>
        <p id="para3"></p>
    </div>


    <!-- JavaScript code Starts here -->
    <script>
        
        /************************************************/
        // Truthy & Falsy Values 
        // Example : When the string is empty, then it has falsy value
        //
        let cityName = "";    // cityName is empty string
        if (cityName) {       // if condition will be false because cityName is empty string
            document.getElementById('para1').innerHTML = 
            `City name is ${cityName}`;
        } else 
            document.getElementById('para1').innerHTML = 
            `City name is BLANK`;
    
        
        /************************************************/
        // Truthy & Falsy Values
        // Example : undefined variable will be false, hence it has falsy value
        //
        let isVaccinated;    // isVaccinated is undefined
        if (isVaccinated) {   // if condition will be false because isVaccinated is undefined
            document.getElementById('para2').innerHTML = 
            "He/She is VACCINATED";
        } else 
            document.getElementById('para2').innerHTML = 
            "He/She is NOT VACCINATED";
    

        /************************************************/
        // Truthy & Falsy Values 
        // Example : 0 (zero) will be false, hence '!0' is 1 i.e true value
        //
        let favNum = 0;    // favNum contains 0
        if (!favNum) {     // if condition will be true because '!0' is 1, which is true
            document.getElementById('para3').innerHTML = 
            "Favorite number cannot be 0 (zero).";
        }

    </script>
    <!-- JavaScript code Ends here -->

</body>
</html>

Output

View original