DEV Community

Cover image for JavaScript Essentials: Handling Null, Undefined, and Safely Accessing Data with ?? and ?.
RakibRahman
RakibRahman

Posted on

JavaScript Essentials: Handling Null, Undefined, and Safely Accessing Data with ?? and ?.

Introduction

There are two types of values in JavaScript. One is Primitive values, and another is objects. null and undefined are primitive data types and behave similarly. Both are treated as falsy values and often used interchangeably. Which sometimes leads to unexpected results due to not being able to distinguish between them. null and undefined are only two JS values that give us exception (TypeError) messages when trying to read property.

Hopefully, this post will help you firm your knowledge of these data types and how to use nullish coalescing operator & optional chaining when dealing with null and undefined values.

Null

  • In JavaScript null means intentional absence of value
  • null is a primitive datatype but treated as an object. Variables with object type are initialized with null.
  • null will be treated as 0 if any primitive operation is applied.
  • null is treated as falsy value for boolean operations.
  • The JSON data format does not support undefined, only null

null

Undefined

  • In JavaScript undefined means not initialized or does not exist.
  • undefined datatype indicates that variable is declared but it does not exist in the memory(no value assigned).
  • Declared variable is always treated as undefined if no value is assigned.
  • If a function does not return anything ,it will always return undefined by default.
  • undefined datatype occurs when variable is uninitialized, specific function parameter is not provided.

undefined

Checking for null and undefined value

JavaScript provides different ways to check for null and undefined. Here’s an example demonstrating how to handle them safely.

checking

The Nullish coalescing operator(??)

The nullish coalescing operator(??) was introduced in ECMAScript 2020. It returns left hand side value if the value is not either undefined or null.If the value is either undefined or null it will return the right hand side value.

For example, when fetching data from the server, if the value is not either null or undefined we can show the received value otherwise it will show the default value as a fallback.The syntax of `nullish coalescing operator is ??.

nullish coalescing operator

Difference between nullish coalescing operator and logical Or operator

At first glance, nullish coalescing operator feels similar to the logical Or (||) operator.The main difference is that nullish coalescing operator only returns default value when left hand side value is either undefined or null. Logical Or (||) operator returns the default value for all other falsy values such false,0,string etc.

or operator

Optional chaining (?.)

Optional chaining (?.) operator is used to access properties and methods calls of an object. If the object value is either null or undefined it will return undefined instead of throwing an error, otherwise it will perform the operation.

Optional Chaining is useful when fetching data from the server, as it wont crash the app if any object property is null or undefined.

optional chaining

Interview questions

Let's look at some interview questions related to null,undefined,nullish coalescing operator and optional chaining.

what is the difference between null and undefined?

Ans: undefined means a variable that has no value. null means the variable was intentionally set to have no value.

What is the type of null?

Ans: object

What is output of following code?

    let a = 5;
    let b;
    console.log(a+b);
Enter fullscreen mode Exit fullscreen mode

Ans: NaN

What does the nullish coalescing operator do?

Ans: It returns the right-hand side operand when the left hand operand is null or undefined. Otherwise, the left hand operand is returned. The syntax is ??.

If a function has no return value specified, what value does it return?

Ans: undefined

What is change can be made that can prevent this code from throwing an error?

 const person = {
    name: 'Mehedi',
    age: 21,
    address: {
        city: 'Dhaka',
        }
            }
console.log(person.address.houseNumber)
Enter fullscreen mode Exit fullscreen mode

Ans: error can be avoided by using Optional chaining(?.), change console.log(person.address.houseNumber); to console.log(person.address?.houseNumber);

References

Conclusion

In this short post, we've looked at null and undefined data types. We also talked about Nullish Coalescing and Optional Chaining operators and when and how to use them. Go through the interviews question to solidify your learning. Hopefully, you learned something new today.

That's all for today. Thank you for reading, and don't forget to connect on LinkedIn or Twitter to get more contents.

If you have any questions or feedback, please leave a comment

Top comments (0)