Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to check for null values in JavaScript ?

How to check for null values in JavaScript ?

The null values show the non-appearance of any object value. It is usually set on purpose to indicate that a variable has been declared but not yet assigned any value.

This contrasts null from the similar primitive value undefined , which is an unintentional absence of any object value.

That is because a variable that has been declared but not assigned any value is undefined, not null.

Approaches: There are many ways to check whether a value is null or not in JavaScript:

  1. By equality Operator (===)
  2. By Object.is() Function
  3. By the typeof Operator

1. By equality Operator (===): By this operator, we will learn how to check for null values in JavaScript by the (===) operator. This operator only passes for null values not for undefined, false, 0, NaN.

Syntax: 

x === y;

Example: The following code snippets show some comparison of objects.

Javascript




<script>
    const object1 = {
        key: "value",
    };
  
    const object2 = {
        key: "value",
    };
  
    console.log(object1 === object2);
    console.log(object1 === object1); 
</script>


Output:

false
true

2. By Object.is() function: This function checks whether two objects’ values are equal or not. If they are the same the two object’s values are the same if both values are null.

Syntax:

Object.is( a, null );

Example:

Javascript




<script>
    let maybeNull = null
  
    // The following is equivalent to 
    // maybeNull == null 
    // or maybeNull == undefined:
    console.log(Object.is(maybeNull, undefined) 
        || Object.is(maybeNull, null))
          
    // Compare to the following:
    console.log(maybeNull == null)
    console.log(maybeNull == undefined)
    console.log(maybeNull === null)
    console.log(Object.is(maybeNull, null))
    console.log(maybeNull === undefined)
    console.log(Object.is(maybeNull, undefined))
  
    maybeNull = undefined
    console.log(maybeNull === undefined || maybeNull === null)
    console.log(maybeNull == null)
    console.log(maybeNull == undefined)
    console.log(maybeNull === null)
    console.log(Object.is(maybeNull, null))
    console.log(maybeNull === undefined)
    console.log(Object.is(maybeNull, undefined)) 
</script>


Output:

true
true
true
true
true
false
false
true
true
true
false
false
true
true

3. By the typeof Operator: Using typeof operator is very useful because if a variable is not declared, it will show ReferenceError. But, the typeof a non-declared value is undefined, so using the typeof is a better way to check for null and undefined variables.

Syntax:

typeof var;

Example: 

Javascript




<script>
    // This will safely check a value to make sure it 
    // has been declared and assigned a value other
    // than null or undefined:
    console.log(typeof undeclaredVariable !== "undefined" 
        && (typeof undeclaredVariable !== "object" 
            || !undeclaredVariable))
  
    // Compare to checking for null using ==, 
    // which will only work for declared variables:
    try { undeclaredVariable == null
    catch (e) { console.log(e) }
    try { undeclaredVariable === null
    catch (e) { console.log(e) }
    try { undeclaredVariable === undefined } 
    catch (e) { console.log(e) }
  
    let declaredButUndefinedVariable
    // Values that have been declared but not 
    // assigned a value will have the value 
    // undefined, which has a typeof undefined
    console.log(typeof declaredButUndefinedVariable 
        !== "undefined" &&
        (typeof declaredButUndefinedVariable !== "object"
            || !declaredButUndefinedVariable))
  
    let stringVariable = "Here's Johnny!"
  
    // If the variable has been both declared and 
    // assigned a value that is neither null or undefined, 
    // we will get true.
    console.log(typeof stringVariable !== "undefined" &&
        (typeof stringVariable !== "object" || !stringVariable))
  
    // This can be used to create a function that will return 
    // false for undefined, undeclared, and null values.
    const isNotNullNorUndefined = 
        (value) => typeof value !== "undefined"
        && (typeof value !== "object" || !value)
    console.log(isNotNullNorUndefined(stringVariable)) 
</script>


Output

...js:7:7)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:22:47
ReferenceError: undeclaredVariable is not defined
    at Object.<anonymous> (/home/guest/sandbox/55da4d93-5c09-4cd3-8be9-a1459e8ed1b0.js:8:7)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:22:47
false
true
true

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments