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.
Potremmo richiedere che i cookie siano attivi sul tuo dispositivo. Utilizziamo i cookie per farci sapere quando visitate i nostri siti web, come interagite con noi, per arricchire la vostra esperienza utente e per personalizzare il vostro rapporto con il nostro sito web.
Clicca sulle diverse rubriche delle categorie per saperne di più. Puoi anche modificare alcune delle tue preferenze. Tieni presente che il blocco di alcuni tipi di cookie potrebbe influire sulla tua esperienza sui nostri siti Web e sui servizi che siamo in grado di offrire.
Cookie essenziali del sito Web
Questi cookie sono strettamente necessari per fornirvi i servizi disponibili attraverso il nostro sito web e per utilizzare alcune delle sue caratteristiche.
Poiché questi cookie sono strettamente necessari per fornire il sito web, rifiutarli avrà un impatto come il nostro sito funziona. È sempre possibile bloccare o eliminare i cookie cambiando le impostazioni del browser e bloccando forzatamente tutti i cookie di questo sito. Ma questo ti chiederà sempre di accettare/rifiutare i cookie quando rivisiti il nostro sito.
Rispettiamo pienamente se si desidera rifiutare i cookie, ma per evitare di chiedervi gentilmente più e più volte di permettere di memorizzare i cookie per questo. L’utente è libero di rinunciare in qualsiasi momento o optare per altri cookie per ottenere un’esperienza migliore. Se rifiuti i cookie, rimuoveremo tutti i cookie impostati nel nostro dominio.
Vi forniamo un elenco dei cookie memorizzati sul vostro computer nel nostro dominio in modo che possiate controllare cosa abbiamo memorizzato. Per motivi di sicurezza non siamo in grado di mostrare o modificare i cookie di altri domini. Puoi controllarli nelle impostazioni di sicurezza del tuo browser.
Cookie di Google Analytics
Questi cookie raccolgono informazioni che vengono utilizzate sia in forma aggregata per aiutarci a capire come viene utilizzato il nostro sito web o quanto sono efficaci le nostre campagne di marketing, o per aiutarci a personalizzare il nostro sito web e l'applicazione per voi al fine di migliorare la vostra esperienza.
Se non vuoi che tracciamo la tua visita al nostro sito puoi disabilitare il tracciamento nel tuo browser qui:
Altri servizi esterni
Utilizziamo anche diversi servizi esterni come Google Webfonts, Google Maps e fornitori esterni di video. Poiché questi fornitori possono raccogliere dati personali come il tuo indirizzo IP, ti permettiamo di bloccarli qui. Si prega di notare che questo potrebbe ridurre notevolmente la funzionalità e l’aspetto del nostro sito. Le modifiche avranno effetto una volta ricaricata la pagina.
Google Fonts:
Impostazioni Google di Enfold:
Cerca impostazioni:
Incorporazione di video Vimeo e Youtube:
Altri cookies
Sono necessari anche i seguenti cookie - Puoi scegliere se permetterli:
Informativa sulla privacy
Puoi leggere i nostri cookie e le nostre impostazioni sulla privacy in dettaglio nella nostra pagina sulla privacy.