There are multiple scenarios where you would generally want to look for the null variable because it can and will crash your whole application. Now that is something that we don’t want to happen. In JavaScript, you can easily check for a null variable with the help of a basic if-else statement. This article will demonstrate this with the help of examples.
Note: Most people confuse null variables with undefined and empty variables for being the same.
Example 1: Checking for Null variable with if – else statement
Simply start by creating a variable and setting its value equal to the keyword null with the following line:
Create another variable with some value in it with the help of the following line:
After that, we are going to create a function that will check variables for a null variable:
function checkNull(ourVar){ if(ourVar !== null){ console.log(«Not a Null variable»); }else{ console.log(«Null variables Detected»); } }
This function simply uses an if-else statement. After that, we are going to pass both our variables one by one to the function checkNull():
checkNull(x); checkNull(y);
Executing this program will provide us with the following result:
The first line in the output is for the variable “x” and from the output we can determine that it is a null variable.
The second line is for the variable “y”; from the output, we can determine that it is not a null variable.
Example 2: Checking for other falsy values
The null value is known as a falsy value in JavaScript, and there are other falsy values in JavaScript. These falsy values include:
NaN
“” (an empty string)
undefined
false
And a few more.
However, they cannot be detected as null, and thus if-else statements cannot determine these variables as null.
To demonstrate this, create a few variables with these falsy values with the following lines of code:
var a = undefined; var b = «»; var c = NaN; var d = false; var e = 0;
After that, simply pass these variables one by one to the checkNull() function that we created in the previous example:
Executing the code will give the following output on the terminal:
All of these variables were considered to be non-null even though all belong to the same family which is “falsy values”.
Conclusion
In JavaScript, if-else statements can be used to determine whether a variable is a null variable or not. For this, we simply set the condition inside the if-else statement as (varName !== null), where varName is the variable identifier, we are checking. In this article, we created a function named checkNull() that determines whether the variable passed inside its argument is a null variable or not.
https://codecubit.com/wp-content/uploads/2022/08/Screenshot-2022-08-11-154212.png216753RoboLinuxhttps://codecubit.com/wp-content/uploads/2022/05/logo340x156.svgRoboLinux2022-08-12 14:47:512022-08-12 14:48:58How to Check if a Variable Is Not Null in JavaScript?
Constraints are said to be limitations or restrictions that are applied to specific columns of a table. Sometimes, it refers to the extra privileges that are assigned to the particular columns. One of that constraints is NOT NULL constraints in SQL database. Whichever column has been specified with the NOT NULL constraint, that column cannot be left without a value. Thus, we have decided to cover the use of the NOT NULL constraint within the SQLite database while implementing this article on Ubuntu 20.04. Before going to the illustration of using the NOT NULL constraint in the SQLite database, we have to open the Ubuntu terminal via the Ctrl+Alt+T instruction and update and upgrade our system using the shown-below instruction.
Make sure to have SQLite C-library of SQL already installed on your Linux system. After that, you need to launch it within the shell terminal with the use of the keyword “sqlite3”. The static shell will be opened within the shell of Ubuntu 20.04 for the SQLite database.
Let’s list all the tables that are found in the SQLite database. Thus, we will be trying the “.tables” instruction to do so. The Sqlite3 database doesn’t contain any database yet (i.e. according to the “.tables” instruction.)
The constraints can only be applied to the columns of a table. If we don’t have any table, then we don’t have any columns. Thus no constraints. Therefore, we have to create a table in the database on which we can apply the NOT NULL constraint. So, the database allows us to use the CREATE TABLE instruction to create one table with the name “Test”. This table will contain a total of 2 columns “ID” and “Name”. The column ID will be of integer type and will be used as a primary key for the table. The “Name” column will be of text type and must not be Null as per the use of the NOT NULL constraint specified at the time of creating a table. Now, we have a new table “Test” in the database as per the “.tables” instruction.
The use of SELECT instruction to fetch the records of a Test table is showing that the table is empty right now. So, we need to add some records to it first.
We will be using the SQL’s INSERT INTO instruction followed by the name of a table and its column to insert the data records within its columns. You need to add records after the “VALUES” keyword followed by the simple brackets holding a total of 10 records. No record has been specified NULL for the column “Name” so far as presented below.
After inserting the records into the Test table, we have tried the SELECT instruction to display all the data on our SQLite shell. It displayed 10 records for the ID and Name column.
Let’s see how the NOT NULL constraint reacts to the spaces and NULL keyword while inserting data into column “Name” of the Test table. So, we have used the empty value “” the place of the “Name” column within the VALUES part of the INSERT INTO instruction. The record has been successfully added to the table Test. After using the SELECT instruction on the shell, we have found that it has been displaying nothing for column “Name” at records 11 and 12 and taking space as a NOT NULL value.
If you try the INSERT INTO instruction with the use of column names that contain a constraint NOT Null and doesn’t add the value for a particular column, then it will throw an error: “1 values for 2 columns” as presented below. To remove this error, you need to put a value for the “Name” column and do not leave it empty.
Let’s put the NULL Keyword within the VALUES part of the INSERT INTO instruction to add the null records for the column “Name” that contains the NOT NULL constraint. Execution of this instruction with the NULL keyword is throwing an error “NOT NULL constraint failed: test.Name”. This means we cannot put NULL as a value to the column “Name” due to its NOT NULL constraint restriction.
Let’s take a look at another example. So, we have created a new table Actor with the three columns ID, Name, and Age via the CREATE TABLE instruction. None of the columns contains a NOT NULL constraint on it.
>>CREATETABLE Actor(ID INTPRIMARYKEY, Name TEXT, Age INT);
Right now the table Actor is empty as per the SELECT “*” instruction below.
We have to put some records in the table “Actor” first with the INSERT INTO instruction. So, we have added 5 records for all three columns: ID, Name, and Age.
We have tried the SELECT instruction to fetch all the newly added records of an “Actor” table. A total of 5 records have been displayed on our screen with no NULL values.
Let’s add a new record within the Actor table that contains a NULL value using the INSERT INTO instruction. So, we have tried the instruction for all the 3 columns and added a NULL value for the column “Age”. The record has been successfully inserted in the table and didn’t throw any error because we haven’t set any NOT NULL constraint for any of the columns of a table “Actor”. The use of SELECT instruction for the table Actor has been displaying all the first 5 added records and the 6th record with a NULL value at its column “Age”.
So, this was about the use of NOT NULL constraints for specific columns of SQLite tables. We have demonstrated how the database reacts to not putting the values within the columns with NOT NULL constraints and how we can use the NULL value with the column values.
Nous pouvons demander que les cookies soient mis en place sur votre appareil. Nous utilisons des cookies pour nous faire savoir quand vous visitez nos sites Web, comment vous interagissez avec nous, pour enrichir votre expérience utilisateur, et pour personnaliser votre relation avec notre site Web.
Cliquez sur les différentes rubriques de la catégorie pour en savoir plus. Vous pouvez également modifier certaines de vos préférences. Notez que le blocage de certains types de cookies peut avoir une incidence sur votre expérience sur nos sites Web et les services que nous sommes en mesure d’offrir.
Cookies Web Essentiels
Ces cookies sont strictement nécessaires pour vous délivrer les services disponibles sur notre site et pour utiliser certaines de ses fonctionnalités.
Du fait que ces cookies sont absolument nécessaires au bon rendu du site, les refuser aura un impact sur la façon dont il fonctionne. Vous pouvez toujours bloquer ou effacer les cookies via les options de votre navigateur et forcer leur blocage sur ce site. Mais le message vous demandant de les accepter/refuser reviendra à chaque nouvelle visite sur notre site.
Nous respectons votre choix de refuser les cookies mais pour éviter de vous le demander à chaque page laissez nous en utiliser un pour mémoriser ce choix. Vous êtes libre de revenir sur ce choix quand vous voulez et le modifier pour améliorer votre expérience de navigation. Si vous refusez les cookies nous retirerons tous ceux issus de ce domaine.
Nous vous fournissons une liste de cookies déposés sur votre ordinateur via notre domaine, vous pouvez ainsi voir ce qui y est stocké. Pour des raisons de sécurité nous ne pouvons montrer ou afficher les cookies externes d’autres domaines. Ceux-ci sont accessibles via les options de votre navigateur.
Cookies Google Analytics
Ces cookies collectent des informations de manière compilée pour nous aider à comprendre comment notre site est utilisé et combien son performantes nos actions marketing, ou pour nous aider à personnaliser notre site afin d’améliorer votre expérience de navigation.
Si vous ne souhaitez pas que votre visite soit pistée sur notre site vous pouvez bloquer ce pistage dans votre navigateur ici :
Autres services externes
Nous utilisons également différents services externes comme Google Webfonts, Google Maps, autres hébergeurs de vidéo. Depuis que ces FAI sont susceptibles de collecter des données personnelles comme votre adresse IP nous vous permettons de les bloquer ici. merci de prendre conscience que cela peut hautement réduire certaines fonctionnalités de notre site. Les changement seront appliqués après rechargement de la page.
Réglages des polices Google :
Réglages Google Map :
Réglages reCAPTCHA :
Intégrations de vidéo Vimeo et Youtube :
Autres cookies
Les cookies suivants sont également requis - Vous pouvez choisir d’autoriser leur utilisation :
Politique de Confidentialité
Vous pouvez lire plus de détails à propos des cookies et des paramètres de confidentialité sur notre Page Mentions Légales.