Javascript logical AND OR NOT operator code syntax

To build a logic most of the times we need to use AND, OR, NOT operators in our conditional statements. Javascript also provide us all AND, OR, NOT operators. Since different programming language has different AND, OR, NOT syntax, sometimes we forget the language specific code syntax. This article or javascript lesson provide you the code syntax or example of the above three operators.

Use of AND Operator:
We have a requirement like: We will pass an employee service length to a javascript function and the function will give us a message ‘One Basic’ if the employee service length in between 0 to 5 years. ‘Three Basic’ if the service length in between 6 to 10 years. Otherwise ‘Five Basic’. So if you simply think you can understand that we need to use AND operator to build the logic. Javascript syntax for AND operator is “&&”. And the sample code will be:

<script type="text/javascript">
function AlertGratuity(nYear)
{
    if(nYear<=5) 
        alert ('One Basic'); 
    //Here is the use of Javascript AND operator "&&"
    else if(nYear>5 && nYear<=10) 
        alert ('Three Basic'); 
    else 
        alert ('Five Basic'); 
} 
AlertGratuity(7); 
</script>

The output will be “Three Basic”.

Use of OR Operator:
We will pass an employee service length and designation to a javascript function and the function will give us a message ‘Three Basic’ if the service length is greater than 5 years or the employee is a Manager. Otherwise ‘One Basic’. So if you think about the logic you need to understand the OR operator to build the logic. Javascript syntax for OR operator is “||”. The code looks like:

<script type="text/javascript">
    function AlertGratuity(nYear,sDesig)
    {
        if(nYear>5 || sDesig=='Manager')
            alert ('Three Basic');
        else
            alert ('One Basic');
    }

    AlertGratuity(3,'Manager');
</script>

Use of NOT Operator
We will pass an employee service length and designation to a javascript function and the function will give us a message ‘Three Basic’ if the service length is greater than 5 years or the employee is not in Executive role. Otherwise ‘One Basic’. So if you think about the logic you need to understand the NOT operator to build the logic. Javascript syntax for NOT operator is “!”. The sample code looks like:

<script type="text/javascript">
    function AlertGratuity(nYear,sDesig)
    {
        // Here is the use of NOT operator
        if(nYear>5 || sDesig!='Executive')
            alert ('Three Basic');
        else
            alert ('One Basic');
    }

    AlertGratuity(3,'Manager');
</script>

I hope now you can understand the javascript AND OR NOT logical operators code syntax. Use those. Happy coding.

Download Code Example

Posted in Client, Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*