JavaScript Comparisons

JavaScript Comparison Operators

JavaScript comparison operators are used in logical statements to compare two variables or values and decide further actions on result.

Below comparisons are based on taking variable age=18

Operator Description Comparing Returns Try it
== Equal to age == 18 true Run the code
age == 19 false Run the code
age == “18” true Run the code
 
=== Equal to value and data type age === 18 true Run the code
age === 19 false Run the code
age === “18” false Run the code
!= Not equal to age != 18 false Run the code
!== Not equal to value and data type age !== 18 false Run the code
age !== “18” true Run the code
age !== “19” true Run the code
> greater than age > 20 false Run the code
< less than age < 20 true Run the code
>= greater than or equal to age >= 18 true Run the code
<= less than or equal to age <= 20 true Run the code

Use of comparison operators

Comparison operators are used with conditional statements to decide which action to be taken further.

if(signalcolor == 'Red') {
    action = 'Stop all vehicles';
}

>Download the code Run the code

JavaScript Logical Operators

Logical operators are used for logic between variables or values.

It is also used to combine more than one conditions with comparison operator

Consider startTime = 9 and endTime = 18 for below logical expressions.

Operator Description example
&& and currentTime > startTime && currentTime < endTime evaluates to true if currentTime = 12 Run the code
|| or currentTime < startTime || currentTime >= endTime evaluates to true if currentTime = 8 Run the code
! not !(startTime == 9) evaluates to false Run the code

JavaScript Bitwise Operators

Bitwise operators work on 32-bits numbers only. So JavaScript number is converted to 32-bit number before being used by bitwise operator. The result is converted back to JavaScript number after completion.

Operator Description Example Same as Result Output
& AND x = 5 & 1 x = 0101 & 0001 0001 1
| OR x = 5 & 1 x = 0101 | 0001 0101 5
~ NOT x = 5 & 1 x = 0101 ~ 0001 1010 10
^ XOR x = 5 & 1 x = 0101 ^ 0001 0100 4
<< Left shift x = 5 << 1 x = 0101 << 0001 1010 10
>> Right shift x = 5 >> 1 x = 0101 >> 0001 0010 2
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .