Pages

Monday, 23 April 2012

Javascript Logical Operators


List of Logical Operators

OperatorOperator nameExample
&&ANDCONDITION : if x > 5 AND x < 20 ; True (both conditions met)
  • x = 10 . TRUE as both conditions true
  • x =25 . False as only one condition true ( x is greater than 5, but not less than 20)
||ORCONDITION : if x > 5 OR x < 20 ; True (both conditions met)
  • x = 10 . TRUE as x is greater than 5
  • x =25 . still TRUE as only one condition needs to be true ( x is greater than 5)
!NOTSCENARIO- Access to company financial data is allowed to all levels of employees except level 1 employees.
if level != 1 then Allow access
(for simple explanation, command not in javascript syntax. examples to come in later lessons)
So if the level of employee is anything but 1, she will be granted access.
level = 1 FALSE (condition not met, disallow access)
level = 3 TRUE (condition met, allow access)


Examples of How Logical Operators are practically used.

Specifying multiple conditions using AND operator.

Entry to a teenager only web portral is allowed for only ages 13 to 19. If we give condition greater than 13, then those with ages 25, 40 and 50 will also be able to enter. similarly if a single condition like less than 19, then ages 5, 6 and others will also qualify as that is less than 19. In many situations we need to specify multiple conditions, then we use the logical operators.
condition
if age > 13 and age < 19 Let the user enter.
When using the AND operator, both the conditions MUST be true. If any one is not met, then the result is false.

Specifying multiple conditions using OR operator.

As opposed to the AND operator, using OR either of the condition has to be true. If one of the two is true, the result will be true.
using the above example of teenagers' website.
Condition
if age < 13 OR age > 19 Notify user that she is not permitted to enter the site.
Either if the age of the visitor is less than 13 or is greater than 19. One of the conditions has to be met to execute the no entry notification.

No comments:

Post a Comment

Thank you for your valuable comment