Learn JavaScript Comparison





In javascript we use Comparison operators to decide if variables or values are diffrenet or equal


In the table below we will use the variable 'a' to learn about the comparison operators:


(we assign the value of 10 to it)

So if a = 10;



Operator Description Comparing Returns Try it
== equal to a == 8 false Try yourself >>
== equal to a == 10 true Try yourself >>
=== equal value and equal type a === 10 true Try yourself >>
=== equal value and equal type a === "10" false Try yourself >>
!= not equal a != 8 true Try yourself >>
> greater than a > 20 false Try yourself >>
>= greater than or equal to a >= 8 true Try yourself >>


We can also a create condition, that will decide on an action that will be performed after the Comparison.


Code Example:

                            
                            if (a < 18) text = "a is less than 18";

                          
                          




Logical Operators


We use the logical operators to figure out the logic between values or variables


Again for learning purposes only, we will use the next variables with value assigned to them:


a = 10;


b = 5;


Operator Description Example Try it
||
if one or both expressions are true,
The or (||) operator returns true, else false
or (a == 2 || b == 2) is false Try yourself >>
&&
If both expressions are true,
The and (&&) operator returns true, else false
and (a < 20 && b > 1) is true Try yourself >>
! not !(a == b) is true Try yourself >>




Conditional Operator


Another operator i would like to talk about is the "Conditional (Ternary) Operator"


The way it works is the Ternary assigns a value to a variable based on some condition


Code Example:

                             
                             var driving license = (age < 18) ? "Too young to drive":"Can drive";

                          
                          
Try yourself >>


If the values is below 18, the variable driving license will be "Too young", otherwise "Can drive".






If we try to compare various types of data we may get unexpected result, check the next list to gain more knowledge about the subject:



Case Value
5 < 10
true
5 < "10"
true
2 == "John"
false
"5" > "12"
true
"5" will be greater than "10", because (alphabetically) 5 is more than 1.
5 < "Jake"
false
"5" == "10"
false








with FreeCodeWiki, you can learn Javascript and programming courses free, our main goal is allowing students to learn to code easily



Navigation