Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Comparison

Comparison Operators

Comparison operators are utilized in logical statements to assess the equality or difference between variables or values.

With x = 5, the table below outlines the comparison operators:

Operator

Description

Comparing

Returns

==

equal to

x == 8

false

x == 5

true

x == “5”

true

===

equal value and equal type

x === 5

true

x === “5”

False

!=

not equal

x != 8

True

!==

not equal value or not equal type

x !== 5

False

x !== “5”

True

x !== 8

True

greater than

x > 8

False

less than

x < 8

True

>=

greater than or equal to

x >= 8

False

<=

less than or equal to

x <= 8

True

How Can it be Used

Comparison operators can be employed in conditional statements to compare values and perform actions based on the outcome.

if (age < 18) text = “Too young to buy alcohol”;

Logical Operators

Logical operators are used to evaluate the relationship between variables or values.

With x = 6 and y = 3, the table below describes the logical operators:

Operator

Description

Example

&&

and

(x < 10 && y > 1) is true

||

or

(x == 5 || y == 5) is false

!

not

!(x == y) is true

Conditional (Ternary) Operator

JavaScript includes a conditional operator that assigns a value to a variable based on a specified condition.

Syntax

variablename = (condition) ? value1:value2 

Example

let voteable = (age < 18) ? “Too young”:“Old enough”;

If the variable age is less than 18, the variable voteable will be assigned the value “Too young”; otherwise, it will be “Old enough.”

Comparing Different Types

Comparing data of different types can lead to unexpected results.

When comparing a string with a number, JavaScript converts the string to a number for the comparison. An empty string is converted to 0, while a non-numeric string is converted to NaN, which is always treated as false.

Case

Value

2 < 12

true

2 < “12”

true

2 < “John”

false

2 > “John”

false

2 == “John”

false

“2” < “12”

false

“2” > “12”

true

“2” == “12”

false

When comparing two strings, “2” is considered greater than “12” because, in alphabetical order, 1 comes before 2.

To ensure accurate results, variables should be converted to the appropriate type before comparison.

age = Number(age);
if (isNaN(age)) {
  voteable = “Input is not a number”;
else {
  voteable = (age < 18) ? “Too young” : “Old enough”;
}