How to compare values using comparison operators in JavaScript.

How to compare values using comparison operators in JavaScript.

·

2 min read

  • The first operator we explore is the Equal to (==) operator. It checks if two values are equal. For example:
const priceOne = 5;
const priceTwo = 10;
console.log(priceOne == priceTwo);
  • Here, we used the Equal to (==) operator to check if the values of priceOne and priceTwo are equal.

  • Comparison operators always return a boolean value. In this case we got false because priceOne and priceTwo are not equal.

  • Now, priceOne and priceTwo have the same value.

      const priceOne = 10;
      const priceTwo = 10;
      console.log(priceOne == priceTwo);
    
    • The second operator we explore is the Not Equal to (!=) operator. It checks if two values are not equal. For example:

        const priceOne = 5;
        const priceTwo = 10;
        console.log(priceOne != priceTwo);
      
      • Now, we got true because priceOne and priceTwo are indeed not equal.
    • Let's look at other types of comparison operators.

    • The Greater than (>) operator checks if the left value is greater than the right value. For example:

    const priceOne = 5;
    const priceTwo = 10;

    console.log(priceOne > priceTwo);
    console.log(priceTwo > priceOne);
  • The Less than (<) operator checks if the left value is less than the right value. For example:
    const priceOne = 5;
    const priceTwo = 10;

    console.log(priceOne < priceTwo);
    console.log(priceTwo < priceOne);
  • Similar to the operators above, there are also the Less than or equal (<=) and Greater than or equal (>=) operators. For example:
    const priceOne = 10;
    const priceTwo = 15;
    const priceThree = 10;

    console.log(priceOne >= priceTwo);
    console.log(priceOne >= priceThree);

    console.log(priceOne <= priceTwo);
    console.log(priceOne <= priceThree)