Written by Creationz
< Previous
|
---|
In programming and coding dynamic web pages comparisons between values of variables become essential.
JavaScript has a range of comparison operators to enable any type of comparison between variables.
The comparison is made to decide over a particular action to be taken. To determine the logic between two variables, we make use of JavaScript’s logical operators.
Conditional operators are special operators which assign a value / variable based on the result of the condition.
With the comparison operators, it’s general comparison of equality or difference. We’ll illustrate the types of comparison and logical operators in the following tables.
Standard Algebraic Operator | JavaScript operator | Sample JavaScript Condition | Meaning of JavaScript Condition |
= | == | X == Y | X is equal to Y |
≠ | != | X != Y | X is not equal to Y |
Standard Algebraic Operator | JavaScript operator | Sample JavaScript Condition | Meaning of JavaScript Condition |
> | > |
X > Y |
X is greater than Y |
< | < | X < Y | X is less than Y |
≥ | >= | X >= Y | X is greater than or equal to Y |
≤ | <= | X <= Y | X is less than or Equal to Y |
Standard Algebraic Operator | JavaScript operator | Sample JavaScript Condition | Meaning of JavaScript Condition |
AND | && |
X < 12 && Y > 20 |
X is less than 12 AND Y is greater than 20 |
OR | || | X > 15 || Y > 20 |
Either X is greater than 15 OR Y is greater than 20 |
NOT | ! | !(X < Y) |
It is not that X is less than Y |
The syntax for the conditional operators is
variable_name = (condition)? value1:value2
If the ‘condition’ is true then, the ‘value1’ is assigned to variable_name otherwise, ‘value2’ is assigned.
The example below will give you deeper understanding about the working of these operators.
It uses four if statements to display a time-sensitive greeting on a welcome page. The script obtains local time from the user’s computer and converts it to a 12-hour clock format. The script wishes you “Good Morning” in the morning and “Good Evening” in the Evening.
<html> <head> <title> Using Relational And Logical Operators </title> <script type=”text/javascript”> <!-- Var time; now=new Date(); // Date is a predefined function and new is used to create //an instance of an object. i.e. it tells that now is refers to function //Date. hour= now.getHours(); if (hour<12) document.write( “<h1>Good Morning!! </h1>”); if (hour >=12) { hour=hour-12; if (hour<6 && hour>12) //&& logically compares truth of two values document.write(“<h1>Good afternoon!!</h1>”); if(hour>=6) document.write(“<h1>Good Evening!!<h1>”); } time=(hour>6)?”Day”:”Evening”; Document.write(<h1>time</h1>); //--> </script> </head> <body> <p> Click refresh to run the script again </p> </body> </html>
This ends the tutorial about the relational, logical and conditional operators in JavaScript.
< Previous
|
---|