How to Define Variables if Null in JavaScript?

Estimated read time 2 min read

In JavaScript, there are different ways to define variables if they are null or undefined. Here are a few examples:

  1. Using the conditional (ternary) operator:
let variable1 = null;
let variable2 = variable1 ? variable1 : "default value";
console.log(variable2); // Output: "default value"

In this example, if variable1 is null or undefined, it will be replaced by the string “default value”.

  1. Using the nullish coalescing operator:
let variable1 = null;
let variable2 = variable1 ?? "default value";
console.log(variable2); // Output: "default value"

The nullish coalescing operator (??) checks if the value on the left side is null or undefined, and if it is, it returns the value on the right side.

  1. Using the typeof operator to check if the variable is undefined:
let variable1;
let variable2 = (typeof variable1 !== 'undefined') ? variable1 : "default value";
console.log(variable2); // Output: "default value"

In this example, the typeof operator is used to check if the variable variable1 is undefined, and if it is, it is replaced by the string “default value”.

  1. Using a default value in a function:
function myFunction(variable1) {
  variable1 = variable1 || "default value";
  console.log(variable1);
}

myFunction(); // Output: "default value"

In this example, the variable1 parameter of the myFunction function is checked if it is null or undefined using the logical OR (||) operator, and if it is, it is replaced by the string “default value”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply