Comparing integers by taking two numbers in JavaScript

Comparing integers is a fundamental operation in JavaScript programming. This tutorial demonstrates how to compare two integers and determine their relationship using JavaScript's comparison operators.

Understanding the Problem

Integer comparison involves determining the relationship between two numbers - whether one is greater than, less than, or equal to another. This operation is essential for sorting algorithms, conditional logic, and data validation. For example, comparing 15 and 10 tells us that 15 is greater than 10.

Comparison Operators in JavaScript

JavaScript provides several comparison operators for integer comparison:

  • > - Greater than
  • < - Less than
  • === - Strict equality (recommended)
  • == - Loose equality
  • >= - Greater than or equal to
  • <= - Less than or equal to

Basic Integer Comparison

// Simple comparisons
let a = 15;
let b = 10;

console.log(a > b);   // true
console.log(a < b);   // false
console.log(a === b); // false

// More examples
console.log(25 === 25); // true
console.log(98 > 100);  // false
true
false
false
true
false

Complete Comparison Function

// Function to compare two integers
function compareIntegers(num1, num2) {
    if (num1 > num2) {
        console.log(`${num1} is greater than ${num2}`);
    } else if (num1 < num2) {
        console.log(`${num1} is less than ${num2}`);
    } else if (num1 === num2) {
        console.log(`${num1} is equal to ${num2}`);
    } else {
        console.log(`${num1} and ${num2} are not comparable`);
    }
}

// Test the function
compareIntegers(15, 10);
compareIntegers(98, 100);
compareIntegers(25, 25);
compareIntegers(0, -5);
15 is greater than 10
98 is less than 100
25 is equal to 25
0 is greater than -5

Return-Based Comparison Function

// Function that returns comparison result
function getComparisonResult(num1, num2) {
    if (num1 > num2) return 1;        // First is greater
    if (num1 < num2) return -1;       // First is smaller
    return 0;                         // Both are equal
}

// Usage examples
console.log(getComparisonResult(20, 15));  // 1
console.log(getComparisonResult(10, 30));  // -1
console.log(getComparisonResult(25, 25));  // 0
1
-1
0

Comparison Table

Comparison Operator Example Result
Greater than > 15 > 10 true
Less than < 10 < 15 true
Equal to === 25 === 25 true

Time Complexity

Integer comparison operations have O(1) constant time complexity, as they perform a fixed number of operations regardless of the input size.

Conclusion

Integer comparison in JavaScript is straightforward using comparison operators. The examples demonstrate how to compare integers and implement comparison functions for various use cases in your applications.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements