Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript comparisons and logical operators


May 06, 2021 JavaScript


Table of contents


JavaScript compares and logical operators


Comparison and logical operators are used to test true or false.


Comparison operator

Comparison operators are used in logical statements to determine whether variables or values are equal.

Given

x-5, the following table explains the comparison operator:
Operator Describe Comparison Returns a value Instance
== Equals x==8 false Examples . . .
x==5 true Examples . . .
=== Absolutely equal (equal value and type) x==="5" false Examples . . .
x===5 true Examples . . .
!= Not equal to x!=8 true Examples . . .
!== Not absolutely equal (one value and type are not equal, or both are not equal) x!=="5" true Examples . . .
x!==5 false Examples . . .
> Greater than x>8 false Examples . . .
< Less than x<8 true Examples . . .
>= Is greater than or equal to x>=8 false Examples . . .
<= Less than or equal to x<=8 true Examples . . .


How to use it

You can use a comparison operator in a conditional statement to compare values and then act on the results:

if (age<18) x="Too young";

You'll learn more about conditional statements in the next section of this tutorial.


The logical operator

Logical operators are used to determine logic between variables or values.

Given the x-6 and y-3, the following table explains the logical operators:

Operator describe example
&& and (x <10 && y> 1) for TRUE
|| or (x == 5 || y == 5) for False
! not ! (x == y) for TRUE

Tip: T he priority of the JavaScript logical operator is:! 、&& 、||。


Conditional operator

JavaScript also contains conditional operators that assign variables based on certain conditions.

Grammar

variablename=(condition)?value1:value2

Example

If the value in the variable age is less than 18, assign the variable voteable "too young" or "age has reached".

voteable = (age <18)? "Age too small": "age has reached";
Try it out . . .