How to Check if Variable is Undefined or Null in Javascript
On the other hand, you can explicitly assign null
to a variable. This means we do not have any meaningful value to assign but we may assign something meaningful later in the code. It simply represents an absence of value for the time being.
In javascript, null
and undefined
both are primitive types. If you do a basic comparison with the help of the equality operator, you will find that both are equal, but they are not if you do the comparison with a strict equality operator.
In the following example, we have 2 global variables, one is undefined
and the other one is null
. Since null
and undefined
both return true when you do the comparison with the equality operator, it does not matter what you use on the right-hand side either null
or undefined
while performing the check. In our case, I am doing it by using undefined
. Please have a look over the code example and steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Check”
and for theh1
element is“Result”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Check</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript
- We have 2 global variables
user1
anduser2
.user1
isnull
anduser2
isundefined
. - We have selected 2 elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are using the equality operator to check if
user2
is equal toundefined
. Depending upon the result, we will display a Boolean value in theh1
element. In our case, the result will beTrue
. - The output of the above step will remain the same even if you change the variable from
user2
touser1
.
let user1 = null; let user2; let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); btnCheck.addEventListener('click', () =>{ result.innerText = user2 == undefined ? 'True' : 'False'; });