Sitemap
Press enter or click to view image in full size

Safe assignment operator

--

The “safe assignment operator” in JavaScript refers to using logical operators to assign values in a safe way, ensuring that you don’t accidentally assign invalid or undefined values. The most common pattern involves using the logical OR (||) or the nullish coalescing operator (??).

1. Logical OR (||)

The || operator assigns a default value if the left-hand expression evaluates to a falsy value (e.g., false, 0, null, undefined, NaN, “”).

let userInput = ""; // Empty string (falsy)
let name = userInput || "Default Name";
console.log(name); // Output: "Default Name"

In this case, if userInput is falsy, name is assigned “Default Name”.

2. Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is similar to ||, but it only checks for null or undefined, making it safer for cases where other falsy values like 0 or “” should be considered valid.

let userInput = ""; // Empty string (not null or undefined)
let name = userInput ?? "Default Name";
console.log(name); // Output: ""

Here, since userInput is not null or undefined, name gets the value of userInput (an empty string), rather than the default value.

Usage in Assignments

Both operators can be used safely in assignment operations to avoid errors caused by null or undefined values.

Get Rakesh Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Practical Example with a Function:

function getConfig(config) {
let timeout = config.timeout || 5000; // Default timeout of 5000 ms if not provided
let retries = config.retries ?? 3; // Default retries of 3 if `null` or `undefined`
return { timeout, retries };
}
const config = { timeout: 0, retries: null };
console.log(getConfig(config));
// Output: { timeout: 5000, retries: 3 }

In this example, the || operator gives 5000 for timeout since 0 is falsy, but ?? allows retries to be assigned 3 only when null or undefined.

--

--

Rakesh Kumar
Rakesh Kumar

Written by Rakesh Kumar

👨‍💻 React Native Developer | ✍️ Writing about React Native, Performance Optimization, and Engineering Practices