亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
What ??= Actually Does
When to Use ??=
1. Setting Default Configuration Values
2. Lazy Initialization of Variables
3. Working with Optional Object Properties
Practical Example: Config Manager
Limitations and Gotchas
Summary
Home Backend Development PHP Tutorial Harnessing the Null Coalescing Assignment Operator (`??=`)

Harnessing the Null Coalescing Assignment Operator (`??=`)

Aug 01, 2025 am 07:43 AM
PHP if Operators

??= assignment operation only takes effect when null or undefined on the left, 1. Used to set the default configuration value, such as user.age ??= 18; 2. Implement lazy initialization of variables, such as cache ??= initializeHeavyResource(); 3. Retain valid values when merging optional object properties, such as userData.email ??= getDefaultEmail(); this operator will not overwrite falsy values such as 0, '' or false, which is safer than ||=, and is suitable for modern environments, ultimately making the code more concise, safe and predictable.

Harnessing the Null Coalescing Assignment Operator (`??=`)

The null coalescing assignment operator ( ??= ) is a concise and powerful feature introduced in modern JavaScript (ES2021) that helps streamline conditional assignments based on null or undefined checks. It's particularly useful when you want to assign a default value to a variable only if it's currently null or undefined .

Harnessing the Null Coalescing Assignment Operator (`??=`)

What ??= Actually Does

The ??= operator works like this:

 a ??= b;

This means:
"If a is null or undefined , assign b to a . Otherwise, leave a unchanged."

Harnessing the Null Coalescing Assignment Operator (`??=`)

It's equivalent to writing:

 if (a == null) {
  a = b;
}

But much more compact and readable.

Harnessing the Null Coalescing Assignment Operator (`??=`)

? Important: ??= only triggers assignment if the left-hand side is null or undefined — not other false values like 0 , '' , or false .

When to Use ??=

1. Setting Default Configuration Values

When working with user-provided options, you often want to fill in defaults only when certain properties are missing.

 function createUser(settings) {
  const user = {};
  user.name = settings.name ?? 'Anonymous';
  user.age ??= settings.age ?? 18;
  user.isActive ??= settings.isActive ?? true;
  return user;
}

Or more cleanly:

 function createUser(settings) {
  const user = { name: 'Anonymous', age: 18, isActive: true };
  user.name ??= settings.name;
  user.age ??= settings.age;
  user.isActive ??= settings.isActive;
  return user;
}

This avoids overwriting with undefined while preserving intentional falsy values.

2. Lazy Initialization of Variables

You can use ??= to initialize expensive or conditional values only when needed.

 let cache;
cache ??= initializeHeavyResource(); // runs only once

Even if cache is reassigned to null later, this pattern allows reinitialization — unlike ||= which would fail on falsy results.

?? Compare with ||= :
||= triggers on any false value ( 0 , '' , false , etc.), which can lead to bugs.
??= is safe because it only cares about null and undefined .

3. Working with Optional Object Properties

When merging partial data, ??= helps preserve existing state.

 const userData = { id: 123, name: 'Alice' };
userData.email ??= getDefaultEmail(userData.name);
userData.role ??= fetchDefaultRole(); // async or computed

This avoids accidentally clearing valid but empty strings or false values.

Practical Example: Config Manager

 class Config {
  constructor() {
    this.apiKey = null;
    this.timeout = 0;
    this.retries = false;
  }

  applyDefaults() {
    this.apiKey ??= process.env.API_KEY;
    this.timeout ??= 5000;
    this.retries ??= 3;
  }
}

Here:

  • timeout is 0 → kept as 0 (not replaced)
  • retries is false → keep as false
  • Only truly missing values ( null ) get defaults

This behavior makes ??= ideal for configuration systems.

Limitations and Gotchas

  • Not available in older environments — requires ES2021 (Node.js 16 , modern browsers). Use Babel or checks in legacy code.
  • Cannot be used directly on object destructuring like default params, but similar logic applications:
 // Destructuring with defaults still uses `=`, not `??=`
const { name = 'Default' } = obj;

// But you can do:
let { apiKey } = obj;
apiKey ??= 'fallback-key';
  • Short-circuiting matters : The right-hand side is evaluated only if the left is null / undefined .
 let x = 1;
x ??= console.log('This won't run'); // no output

Summary

Use ??= when:

  • You want to assign defaults only for null / undefined
  • You need to preserve false values like 0 , '' , or false
  • You're doing lazy initialization or merging partial data

Avoid ||= in these cases — it's too broad.

Basically:
??= = "only assign if really missing"
||= = "assign if false" — often too aggressive

With ??= , your code becomes cleaner, safer, and more predictable when handling optional values.

The above is the detailed content of Harnessing the Null Coalescing Assignment Operator (`??=`). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Demystifying Type Juggling: The Critical Difference Between `==` and `===` Demystifying Type Juggling: The Critical Difference Between `==` and `===` Jul 30, 2025 am 05:42 AM

Using === instead of == is the key to avoid PHP type conversion errors, because == will cause unexpected results, and === compare values and types at the same time to ensure accurate judgment; for example, 0=="false" is true but 0==="false" is false, so when dealing with return values that may be 0, empty strings or false, === should be used to prevent logical errors.

When Not to Use the Ternary Operator: A Guide to Readability When Not to Use the Ternary Operator: A Guide to Readability Jul 30, 2025 am 05:36 AM

Avoidnestedternariesastheyreducereadability;useif-elsechainsinstead.2.Don’tuseternariesforsideeffectslikefunctioncalls;useif-elseforcontrolflow.3.Skipternarieswithcomplexexpressionsinvolvinglongstringsorlogic;breakthemintovariablesorfunctions.4.Avoid

Beyond `if-else`: Exploring PHP's Alternative Control Structures Beyond `if-else`: Exploring PHP's Alternative Control Structures Jul 30, 2025 am 02:03 AM

The alternative control structure of PHP uses colons and keywords such as endif and endfor instead of curly braces, which can improve the readability of mixed HTML. 1. If-elseif-else starts with a colon and ends with an endif, making the condition block clearer; 2. Foreach is easier to identify in the template loop, and endforeach clearly indicates the end of the loop; 3. For and while are rarely used, they are also supported. This syntax has obvious advantages in view files: reduce syntax errors, enhance readability, and is similar to HTML tag structure. But curly braces should continue to be used in pure PHP files to avoid confusion. Therefore, alternative syntax is recommended in templates that mix PHP and HTML to improve code maintainability.

The Null Coalescing Operator (??): A Modern Approach to Handling Nulls The Null Coalescing Operator (??): A Modern Approach to Handling Nulls Aug 01, 2025 am 07:45 AM

Thenullcoalescingoperator(??)providesaconcisewaytoassigndefaultvalueswhendealingwithnullorundefined.1.Itreturnstheleftoperandifitisnotnullorundefined;otherwise,itreturnstherightoperand.2.UnlikethelogicalOR(||)operator,??onlytriggersthefallbackfornull

Refactoring Nested `if` Hell: Strategies for Cleaner Conditional Logic Refactoring Nested `if` Hell: Strategies for Cleaner Conditional Logic Jul 30, 2025 am 04:28 AM

Useguardclausestoreturnearlyandflattenstructure.2.Extractcomplexconditionsintodescriptivefunctionsorvariablesforclarityandreuse.3.Replacemultipleconditioncombinationswithalookuptableorstrategypatterntocentralizelogic.4.Applypolymorphismtoeliminatetyp

Optimizing Conditional Logic: Performance Implications of `if` vs. `switch` Optimizing Conditional Logic: Performance Implications of `if` vs. `switch` Aug 01, 2025 am 07:18 AM

Sometimes it will affect performance, depending on the language, compiler optimization and logical structure; 1. If statements are executed in order, and the worst case time complexity is O(n), the most likely condition should be placed first; 2. The switch statement can be optimized by the compiler to a jump table of O(1) when the conditions are continuous integers, many branches and the values are compiled constants; 3. When a single variable is compared with multiple constant integers and there are many branches and switches are faster; 4. When it involves scope judgment, complex conditions, non-integer types or fewer branches, if if is more suitable or has similar performance; 5. Different languages (such as C/C, Java, JavaScript, C#) have different optimization degrees of switches, and they need to be tested in combination with actual testing; Swi should be used first

Crafting Bulletproof Conditionals with Strict Type Comparisons Crafting Bulletproof Conditionals with Strict Type Comparisons Jul 30, 2025 am 04:37 AM

Alwaysusestrictequality(===and!==)inJavaScripttoavoidunexpectedbehaviorfromtypecoercion.1.Looseequality(==)canleadtocounterintuitiveresultsbecauseitperformstypeconversion,making0==false,""==false,"1"==1,andnull==undefinedalltrue.2

Leveraging Short-Circuit Evaluation with `&&` and `||` for Performance Leveraging Short-Circuit Evaluation with `&&` and `||` for Performance Aug 01, 2025 am 07:31 AM

Use&&toskipexpensiveoperationsandguardagainstnull/undefinedbyshort-circuitingonfalsyvalues;2.Use||tosetdefaultsefficiently,butbewareittreatsallfalsyvalues(like0)asinvalid,soprefer??fornull/undefinedonly;3.Use&&or||forconciseconditiona

See all articles