Comparison Operators

Comparison operatorsopen in new window are used to compare the values two operands. Some comparison operators will also compare the operands' data types.

Equality Operators

JavaScript has strict (===) and type-converting (==) equality operators. In the latter, JavaScript will automatic convert the operands to be of the same type, before comparing the values, thus ignoring the operands' original data type. With strict comparison, the operands values and data types must both match in order for them to be equal.

console.log(1 == 1)             // true
console.log('1' == 1)           // true
console.log(1 === 1)            // true
console.log('1' === 1)          // false

console.log(0 == false)         // true
console.log(null == undefined)  // true 
console.log(0 === false)        // false
console.log(null === undefined) // false

JavaScript also has strict (!==) and type-converting (!=) inequality operators.

console.log(1 != 2)       // true
console.log(1 != '1')     // false
console.log(1 !== 2)      // true
console.log(1 !== '1')    // true

console.log(1 != true)    // false
console.log(0 != false)   // false
console.log(1 !== true)   // true
console.log(0 !== false)  // true

NOTE

In almost all cases, it is best use the strict equality operators.

Relational Operators

Relational operators will compare the two operands in comparison with each other. These comparison include the greater than (>), greater than or equal to (>=), less than (<), and less than or equal to (<=) operators.

NOTE

Relational operators can be used with strings. String are compared based on their unicode values.

Greater Than

The greater than operator (>) will return true if the left operand is greater than the right operand.

console.log(4 > 3)                // true
console.log(3 > 4)                // false
console.log(3 > 3)                // false

console.log('banana' > 'apple')   // true
console.log('Banana' > 'apple')   // false
// In unicode uppercase letters come before lowercase letters

Greater Than or Equal To

The greater than or equal to operator (>=) will return true if the left operand is greater than or equal to the right operand.

console.log(4 >= 3)     // true
console.log(3 >= 4)     // false
console.log(3 >= 3)     // true

Less Than

The less than operator (<) will return true if the left operand is less than the right operand.

console.log(3 < 4)              // true
console.log(4 < 3)              // false
console.log(3 < 3)              // false

console.log('apple' < 'banana') // true
console.log('apple' < 'Banana') // false
// In unicode uppercase letters come before lowercase letters

Less Than or Equal To

The less than or equal to operator (<=) will return true if the left operand is less than or equal to the right operand.

console.log(3 <= 4)              // true
console.log(4 <= 3)              // false
console.log(3 <= 3)              // true