One place for hosting & domains

# Comparison

## Understanding Comparison and Logical Operators in JavaScript

### Introduction

The field of computer science has many foundations in mathematical logic. If you have a familiarity with logic, you know that it involves truth tables, Boolean algebra, and comparisons to determine equality or difference.

The JavaScript programming language uses operators to evaluate statements that can aid in control flow within programming.

In this tutorial, we’ll go over logical operators. These are commonly used with conditional statements, and the `if`, `else`, and `else if` keywords, as well as the ternary operator. If you are interested in learning more about conditional statements first, refer to How To Write Conditional Statements in JavaScript.

## Comparison Operators

In JavaScript, there are a number of comparison operators that you can use to evaluate whether given values are different or equal, as well as if a value is greater than or less than another. Often, these operators are used with stored values in variables.

Comparison operators all return a Boolean (logical) value of `true` or `false`.

The table below summarizes the comparison operators available in JavaScript.

Operator What it means
`==` Equal to
`!=` Not equal to
`===` Strictly equal to with no type conversion
`! ==` Strictly unequal to with no type conversion
`>` Greater than
`>=` Greater than or equal to
`<` Less than
`<=` Less than or equal to

Let’s go into each operator in detail.

### Equality

The equality operator measures whether values on either side of the operator are equal.

Let’s consider the following:

``````let x = 3;

x == 3;
``````

Because `3` is equivalent to `3`, the output received will be the Boolean value of `true`.

``````Outputtrue
``````

If we instead test whether `x` is equal to another integer, we’ll receive output stating that the statement is validated to be false.

``````let x = 3;

x == 5;
``````
``````Outputfalse
``````

With this equivalency expression, you can also test other data types such as strings and Booleans.

We’ll use a string example below.

``````let shark = 'sammy';

shark == 'sammy';
shark == 'taylor';
``````
``````Outputtrue
false
``````

In the first instance, the expression returned `true` because the strings were equivalent. In the second instance, of `shark == 'taylor'`, the expression returned `false` because the strings were not equal.

Worth noting, is that the `==` operator is not a strict equivalency, so you can mix numbers and strings that evaluate to being equivalent. Consider the following example.

``````let x = 3;

x == '3';
``````

Even though the first line uses a number data type, and the second line tests `x` against a string data type, both values equal 3, and the output you will receive indicates that the expression is true.

``````Outputtrue
``````

Because this operator is not strict about data type, it can support users entering strings instead of numbers, for example. There is no need to convert data types to test equivalency.

There are many cases where you may use comparison operators like the `==` operator. You may want to test equivalency when grading a test, for example. That way you can validate whether a given answer is correct or not.

``````let answer = 10;
let response = prompt("What is 5 + 5?");

console.log("You're correct!");
}
``````

Here, if the student enters `10` in response to the question when prompted, they will receive the feedback that they are correct.

There are many potential applications of comparison operators in JavaScript, and they will help you control the flow of your program.

Now that you have a foundation with a few examples for `==`, we’ll be a bit briefer going forward.

### Inequality

The `!=` operator tests inequality, to determine whether the values on either side of the operator are not equal.

Let’s consider an example.

``````let y = 8;

y != 9;
``````

For this example, `8` does not equal `9`, so the expression will be evaluated to be `true`:

``````Outputtrue
``````

For a statement of inequality to be considered `false`, the two values on either side would need to actually be equal, as in the following.

``````let y = 8;

y != 8
``````
``````Outputfalse
``````

In this second example, the two values on either side of the operator are equal, so the expression is not true.

### Identity

The `===` operator determines whether two values are both of equal value and of equal type. This is also known as a strict equality operator. This means you cannot mix number and string data types.

Here’s an example:

``````let z = 4;

z === 4;

z === '4';
``````

``````Outputtrue

false
``````

The example indicates that `z` is strictly equal to `4` (as it is assigned the numeric value of `4`), but that it is not strictly equal to the string `'4'`.

Because this operator is strict, you will need to keep in mind that you may need to convert user-entered data from one data type to another, for instance, when working with the identity operator. This may help you keep data types consistent throughout your program.

### Non Identity

Like `===`, the operator `!==` evaluates a strict inequality, which considers both the value and the type of the operands on either side of the operator.

We’ll review the following examples.

``````let a = 18;

a !== 18;

a !== '18';

a !== 29;
``````

The output for the above will be as follows.

``````Outputfalse

true

true
``````

In this example, since `a` does strictly equal `18`, the first expression evaluates to `false` as we are testing inequality. In the next two examples, `a` is determined to be unequal to the string `'18'` and the number `29`, so those two expressions evaluate to `true` (since they are not equal).

### Greater than

The greater than symbol in JavaScript may be familiar to you from math: `>`. This evaluates whether one value (on the left side of the expression) is greater than another value (on the right side of the expression).

Like the `==` operator above, the greater than operator is not strict, and therefore will allow you to mix strings and numbers.

Let’s consider the following examples.

``````let f = 72;

f > 80;

f > '30';
``````

``````Outputfalse

true
``````

In the first instance, `72` is less than `80`, so the first expression evaluates to `false`. In the second instance, `72` is in fact greater than `'30'`, and the operator does not care that the number is a string, so the expression evaluates to `true`.

### Greater than or equal

Similarly, the operator for greater than or equal to will evaluate whether one operand meets the threshold of the other. This operator is typed as `>=` a kind of compound between greater than (`>`) and the equal sign (`=`).

Our examples:

``````let g = 102;

g >= 90;

g >= 103;
``````
``````Outputtrue

false
``````

Because `102` is a larger number than `90`, it is considered to be greater than or equal to `90`. Because `102` is less than `103`, it is `false` to state that `102 >= 103`. If either `90` or `103` were a string data type, the expressions would also evaluate the same.

### Less than

The less than operator appears as the mirror version of the greater than operator: `<`.

Consider the following examples as a demonstration.

``````let w = 1066;

w < 476;

w < 1945;
``````
``````Outputfalse

true
``````

Here, `1066` is greater than `476`, so the expression evaluates to `false`. However, `1066` is less than `1945`, so the second statement evaluates to `true`. Again, the `476` or `1945` values could also be strings.

### Less than or equal

The opposite of greater than or equal, the less than or equal operator — `<=` — will evaluate whether the value on the left side of the operator is less than or equal to the value on the right side.

Here are a few examples.

``````let p = 2001;

p <= 1968;

p <= 2001;

p <= 2020;
``````
``````Outputfalse

true

true
``````

The first expression evaluates to `false` because `2001` is not less than or equal to `1968`. In the second expression, because the variable and `2001` are equal values, the output is `true`. In the third expression, the output is also `true` because `2001` is less than `2020`. Again, these values could also be represented as strings, as in `'2001'`, and would evaluate in the same manner.

Note: Be sure not to confuse the less than or equal operator (`<=`) with the arrow function (`=>`) in JavaScript. Learn more about arrow functions in our tutorial Understanding Arrow Functions in JavaScript.

To understand how these comparison operators can work together in a program, refer to our `grades.js` example in our How To Write Conditional Statements in JavaScript tutorial.

## Logical Operators

In JavaScript, there are three logical operators, which connect two or more programming statements to return a `true` (also called “truthy”) or `false` (“falsy”) value. These are most often used with Boolean (logical) types, but can be applied to values of any data type.

These logical operators are summarized in the table below.

Operator Syntax Description
AND `&&` Returns `true` if both operands are `true`
OR || Returns `true` if either operand is `true`
NOT `!` Returns `true` if operand is `false`

Let’s review each of these operators in more detail.

### AND

The AND operator is represented by two ampersands — `&&` — it will return `true` if the operands to the left and right evaluate to be true.

For example, with AND we can check if something is both high quality and has a low price.

``````// High quality and low price are true
const highQuality = true;
const lowPrice = true;

(highQuality && lowPrice);
``````
``````Outputtrue
``````

Since both variables evaluate to be `true`, the AND operation within the parentheses returns `true`. If either one of the variables were initialized as `false`, the `&&` expression would evaluate to `false`.

### OR

The OR operator is represented by two pipes — `||` — it will return `true` if one of the operands is true.

In this example, we’ll check if something is either `highQuality` or `lowPrice`.

``````// Only low price is true
const highQuality = false;
const lowPrice = true;

(highQuality || lowPrice);
``````
``````Outputtrue
``````

Since one of the two conditions (`highQuality` or `lowPrice`) was `true`, the whole operation returns `true`. This would only evaluate to `false` if both conditions were `false`.

### NOT

The NOT operator is represented by an exclamation point — `!` — it will return `true` if the operand is set to `false`, and vice versa.

``````const highQuality = true;

!(highQuality);
``````
``````Outputfalse
``````

In the above statement, `highQuality` has the value of `true`. With the NOT operator, we are checking to see if `hiqhQuality` evaluates to `false`. If it were `false`, the output would return `true`, but since it is `true`, the output returns `false`.

The NOT operator is a bit tricky to understand at first. The important part to remember is that NOT checks whether something evaluates to be false.

## Conclusion

Logical operators are the building blocks of flow control in JavaScript programming. Using these operators effectively will help you develop programs that evaluate statements and move to the next stage based on whether a statement is true or false.

To continue learning more about JavaScript, check out our How To Code in JavaScript series, and our JavaScript tag.

## How To Use Comparison and IS NULL Operators in SQL

### Introduction

In certain Structured Query Language (SQL) statements, `WHERE` clauses can be used to limit what rows the given operation will affect. They do this by defining specific criteria that each row must meet for it to be impacted, known as a search condition. Search conditions are made up of one or more predicates, which are special expressions that evaluate to either “true,” “false,” or “unknown,” and operations only affect those rows for which every predicate in the `WHERE` clause evaluates to “true.”

SQL allows users to write search conditions that include a variety of different types of predicates, each of which use a specific operator to evaluate rows. This guide will outline two types of predicates and the operators they use: comparison operators and the `IS NULL` operator.

Although this guide will exclusively use `SELECT` statements in its examples, the concepts explained here can be used in a number of SQL operations. In particular, `WHERE` clauses and their search conditions are critical components of `UPDATE` and `DELETE` operations.

## Prerequisites

In order to follow this guide, you will need a computer running some type of relational database management system (RDBMS) that uses SQL. The instructions and examples in this guide were validated using the following environment:

• A server running Ubuntu 20.04, with a non-root user with administrative privileges and a firewall configured with UFW, as described in our initial server setup guide for Ubuntu 20.04.
• MySQL installed and secured on the server, as outlined in How To Install MySQL on Ubuntu 20.04. This guide was verified with a newly-created user, as described in Step 3.
• You’ll also need a database with some tables loaded with sample data which you can use to practice using the comparison and `IS NULL` operators. We encourage you to go through the following Connecting to MySQL and Setting up a Sample Database section for details on how to connect to a MySQL server and create the testing database used in examples throughout this guide.

Note: Please note that many RDBMSs use their own unique implementations of SQL. Although the commands outlined in this tutorial will work on most RDBMSs, including PostgreSQL and SQLite, the exact syntax or output may differ if you test them on a system other than MySQL.

### Connecting to MySQL and Setting up a Sample Database

If your SQL database system runs on a remote server, SSH into your server from your local machine:

``` Then open up the database server prompt. If you’re using MySQL, do so by running the following command, making sure to replace sammy with the name of your MySQL user account: From the prompt, create a database named comparison_null_db: CREATE DATABASE comparison_null_db; If the database was created successfully, you’ll receive output like this: OutputQuery OK, 1 row affected (0.01 sec) To select the comparison_null_db database, run the following USE statement: OutputDatabase changed After selecting comparison_null_db, create a table within it. To follow along with the examples used in this guide, imagine that you and a group of your friends all decide to become more physically active and take up running as exercise. To this end, your friends all set a personal goal for how many miles they want to run in the next month. You decide to track your friends’ mileage goals, as well as the number of miles they actually ran, in an SQL table that has the following three columns: name: each of your friends’ names, expressed using the varchar data type with a maximum of 15 characters goal: each friends’ goal for how many miles they hoped to run over the past month, expressed as an integer using the int data type result: the number of miles each friend ultimately ran over the course of the month, again expressed as an int Run the following CREATE TABLE statement to create a table named running_goals that has these three columns: CREATE TABLE running_goals ( name varchar(15), goal int, result int ); OutputQuery OK, 0 rows affected (0.012 sec) Then load the running_goals table with some sample data. Run the following INSERT INTO operation to add seven rows of data representing seven of your friends, their running goals, and their results: INSERT INTO running_goals VALUES ('Michelle', 55, 48), ('Jerry', 25, NULL), ('Milton', 45, 52), ('Bridget', 40, NULL), ('Wanda', 30, 38), ('Stewart', 35, NULL), ('Leslie', 40, 44); OutputQuery OK, 7 rows affected (0.004 sec) Records: 7 Duplicates: 0 Warnings: 0 Note that three of these rows’ result values are NULL. For the purposes of this example, assume that these friends just haven’t reported the number of miles they ran over the past month so their result values were entered as NULL. With that, you’re ready to follow the rest of the guide and begin learning how to use the comparison and IS NULL operators in SQL. Understanding WHERE Clause Predicates In any SQL operation that reads data from an existing table, you can follow the FROM clause with a WHERE clause to limit what data the operation will affect. WHERE clauses do this by defining a search condition; any row that doesn’t meet the search condition is excluded from the operation, but any row that does is included. A search condition is made up of one or more predicates, or expressions that can evaluate one or more value expressions and return a result of either “true,” “false,” or “unknown.” In SQL, a value expression — also sometimes referred to as a scalar expression — is any expression that will return a single value. A value expression can be a literal value, like a string or numeric value, a mathematical expression, or a column name. Note that it’s almost always the case that at least one value expression in a WHERE clause predicate is the name of a column in the table referenced in the operation’s FROM clause. When running SQL queries that contain a WHERE clause, the DBMS will apply the search condition to every row in the logical table defined by the FROM clause. It will then return only the rows for which every predicate in the search condition evaluates to “true.” The SQL standard defines 18 types of predicates, although not every RDBMS includes each of them in its implementation of SQL. Here are five of the most commonly used predicate types, as well as a brief explanation of each one and the operators they use: Comparison: Comparison predicates compare one value expression with another; in queries, it’s almost always the case that at least one of these value expressions is the name of a column. The six comparison operators are: =: tests whether the two values are equivalent <>: tests whether two values are not equivalent <: tests whether the first value is less than the second >: tests whether the first value is greater than the second <=: tests whether the first value is less than or equal to the second >=: tests whether the first value is greater than or equal to the second Null: Predicates that use the IS NULL operator test whether values in a given column are NullRange: Range predicates use the BETWEEN operator to test whether one value expression falls between two othersMembership: This type of predicate uses the IN operator to test whether a value is a member of a given setPattern Match: Pattern matching predicates use the LIKE operator to test whether a value matches a string pattern As mentioned in the introduction, this guide focuses on how to use SQL’s comparison and IS NULL operators to filter data. If you’d like to learn how to use the BETWEEN or IN operators with range and membership predicates, respectively, we encourage you to check out this guide on How To Use the BETWEEN and IN Operators in SQL. Alternatively, if you’d like to learn how to use the LIKE operator to filter data based on a string pattern containing wildcard characters, follow our guide on How To Use Wildcards in SQL. Lastly, if you’d like to learn more about WHERE clauses generally, you may be interested in our tutorial on How To Use WHERE Clauses in SQL. Comparison Predicates WHERE clause comparison predicates use one of six comparison operators to compare one value expression with another. They typically follow a syntax like this: SELECT column_list FROM table_name WHERE column_name OPERATOR value_expression; Following the WHERE keyword is a value expression which, in most SQL operations, is the name of a column. Providing a column name as a value expression in a search condition tells the RDBMS to use each row’s value from that column as the value expression for that row’s iteration of the search condition. Because the database system applies search conditions to each row in sequence, the comparison operator will then include or filter out a row based on whether the search condition is true for its value from the specified column. To illustrate, run the following query which will return values from the running_goals table’s name and goal columns. Note how the WHERE clause uses a comparison predicate that will cause the query to only return rows whose goal value is equal to 40: SELECT name, goal FROM running_goals WHERE goal = 40; Only two of your friends’ goals were to run exactly 40 miles over the past month, so the query returns just those two rows: Output+---------+------+ | name | goal | +---------+------+ | Bridget | 40 | | Leslie | 40 | +---------+------+ 2 rows in set (0.00 sec) To illustrate how the other comparison operators work, run the following queries which are identical to the previous example except that each uses a different comparison operator. The <> operator tests whether two values are not equivalent, so this query returns every row whose goal value is not equal to 40: SELECT name, goal FROM running_goals WHERE goal <> 40; Output+----------+------+ | name | goal | +----------+------+ | Michelle | 55 | | Jerry | 25 | | Milton | 45 | | Wanda | 30 | | Stewart | 35 | +----------+------+ 5 rows in set (0.00 sec) The < operator tests whether the first value expression is less than the second: SELECT name, goal FROM running_goals WHERE goal < 40; Output+---------+------+ | name | goal | +---------+------+ | Jerry | 25 | | Wanda | 30 | | Stewart | 35 | +---------+------+ 3 rows in set (0.00 sec) The > operator tests whether the first value expression is greater than the second: SELECT name, goal FROM running_goals WHERE goal > 40; Output+----------+------+ | name | goal | +----------+------+ | Michelle | 55 | | Milton | 45 | +----------+------+ 2 rows in set (0.00 sec) The <= operator tests whether the first value is less than or equal to the second: SELECT name, goal FROM running_goals WHERE goal <= 40; Output+---------+------+ | name | goal | +---------+------+ | Jerry | 25 | | Bridget | 40 | | Wanda | 30 | | Stewart | 35 | | Leslie | 40 | +---------+------+ 5 rows in set (0.00 sec) The >= operator tests whether the first value is greater than or equal to the second: SELECT name, goal FROM running_goals WHERE goal >= 40; Output+----------+------+ | name | goal | +----------+------+ | Michelle | 55 | | Milton | 45 | | Bridget | 40 | | Leslie | 40 | +----------+------+ 4 rows in set (0.00 sec) The equivalence (=) and inequivalence (<>) operators work with string values as one might expect. The following query returns every row’s name value that’s equal to 'Leslie': SELECT name FROM running_goals WHERE name="Leslie"; Because there’s only one friend in the table named “Leslie,” the query just returns that row: Output+--------+ | name | +--------+ | Leslie | +--------+ 1 row in set (0.00 sec) When comparing string values, the <, >, <=, and >= operators all evaluate how the strings relate alphabetically. Put differently, if you write a predicate that tests whether one string is “less than” another, you’re testing whether the first string comes before the second alphabetically. Likewise, if your predicate tests whether one string is “greater than” another, you’re testing whether the first string comes after the second one alphabetically. To illustrate, run the following query. This will return the name and goal values of every row whose name value is “less than” the letter 'M'. In other words, the search condition will evaluate to “true” for every row whose name value comes before M alphabetically: SELECT name FROM running_goals WHERE name < 'M'; Output+---------+ | name | +---------+ | Jerry | | Bridget | | Leslie | +---------+ 3 rows in set (0.00 sec) Notice that this result set doesn’t include Michelle or Milton. This is because, alphabetically, the single letter “M” comes before any string that starts with the letter “M” and has more than one letter, so these two friends are excluded from this result set. Null Predicates In SQL, NULL is a reserved keyword used to represent missing or unknown values. Null is a state, rather than an actual value; it does not represent zero or an empty string. You can use the IS NULL operator to test whether a given value expression is Null: . . . WHERE column_name IS NULL . . . With this type of predicate, the database system will look at every row’s value from the specified column and evaluate whether or not each one is Null. If values in the column are indeed Null, the search condition will evaluate to “true” for those rows and they will be included in the result set. To illustrate, run the following query which returns the name and result columns: SELECT name, result FROM running_goals WHERE result IS NULL; The search condition in this query’s WHERE clause tests whether each row’s result value is Null. If so, the predicate evaluates to “true” and the row is included in the result set: Output+---------+--------+ | name | result | +---------+--------+ | Jerry | NULL | | Bridget | NULL | | Stewart | NULL | +---------+--------+ 3 rows in set (0.00 sec) Because three of your friends haven’t yet reported the number of miles they ultimately ran over the past month, those values were recorded as NULL when you loaded the table with data. Consequently, the search condition in the query evaluates to “true” for these three rows, so they’re the only ones included in the result set. Conclusion By following this guide, you learned how to use SQL’s comparison and IS NULL operators in WHERE clauses to limit the rows that an operation will affect. While the commands shown here should work on most relational databases, be aware that every SQL database uses its own unique implementation of the SQL standard. You should consult your DBMS’s official documentation for a more complete description of each command and their full sets of options. If you’d like to learn more about working with SQL, we encourage you to check out the other tutorials in this series on How To Use SQL. ```
``` Source link ```
``` ```
``` ```
``` ```
``` Recent Posts How to Start a Blog in 7 Easy Steps Getting Started on the Linode Platform A Guide to API Formats: The Different Types of APIs Using Redis Transaction Blocks A Javascript Objects Tutorial Recent CommentsArchives June 2022 May 2022 March 2022 February 2022 January 2022 December 2021 November 2021 October 2021 September 2021 August 2021 July 2021 June 2021 May 2021 April 2021 March 2021 February 2021 January 2021 December 2020 November 2020 October 2020 September 2020 August 2020 July 2020 June 2020 May 2020 April 2020 March 2020 February 2020 January 2020 December 2019 November 2019 October 2019 September 2019 August 2019 July 2019 June 2019 May 2019 April 2019 March 2019 February 2019 January 2019 December 2018 November 2018 October 2018 September 2018 July 2016 Categories blog client Meta Log in Entries feed Comments feed WordPress.org ```
``` ```
``` ```
``` We Accept © 2012-2018 All rights reserved by Xpres Servers & Hassan Latif window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-24390847-5'); Sign inNew Account Remember meRegistration confirmation will be e-mailed to you.Forgot Your Password ? /* <![CDATA[ */ var idzUIAjax = {"ajaxurl":"https:\/\/www.xpresservers.com\/wp-admin\/admin-ajax.php","smart_nonce":"cfc27010c0"}; /* ]]> */ /* <![CDATA[ */ var wpcf7 = {"api":{"root":"https:\/\/www.xpresservers.com\/wp-json\/","namespace":"contact-form-7\/v1"},"cached":"1"}; /* ]]> */ ```