JavaScript Not-Equal

JavaScript Not-Equal (!=) Comparison Operator is used to check if two values are not equal. Not-Equal operator returns a boolean value. The return value is true if the two values are not equal, else, the return vale is true.

Not-Equal Operator Symbol

The symbol used for Not-Equal Operator is !=.

Syntax

The syntax to use Not-Equal Operator with operands is

operand1 != operand2

Each operand can be a value or a variable.

Since Not-Equal operator returns a boolean value, the above expression can be used as a condition in If-statement.

Not-Equal operator does not check the type of values being compared. For example, the expression 5 != '5' returns false in JavaScript.

Examples

In the following example, we take two values in variables: x and y; and check if the values in x and y are not equal using Not-Equal Operator.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = 4;
        var y = 7;
        var result = x != y;
        document.getElementById('output').innerHTML += 'Are values of x and y not equal?  ' + result;
    </script>
</body>
</html>

Since not-equal operator does not check the type of the operands, but the values alone, let us check if 5 is not equal to '5'. Not-equal operator must return false.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = 5;
        var y = '5';
        var result = x != y;
        document.getElementById('output').innerHTML += 'Are values of x and y not equal?  ' + result;
    </script>
</body>
</html>

In the following example, let us use the not-equal operator in the If statement’s condition.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = 'apple';
        var y = 'banana';
        if (x != y) {
            document.getElementById('output').innerHTML += 'x and y are not equal.';
        } else {
            document.getElementById('output').innerHTML += 'x and y are equal.';
        }
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned about Not-Equal Comparison Operator, its syntax, and usage with examples.