-2

I saw the following in a piece of Typescript code:

const arrayAA: Record<
    someSchema['propX'],
    typeof arrayBB
    > = {};
    
for (const varB of arrayBB) {
    (arrayAA[someStringValue] ??= []).push(varB)
}

What does "??=" mean here?

I can't find anything about "??=" in the docs.

==========

(Edit after the comments)

Ok, it was asked before (although I did a search for "??=" on StackOverflow)

So, this code could (should?) be rewritten as:

if (arrayAA[someStringValue] === undefined || arrayAA[someStringValue] === null) { 
    arrayAA[someStringValue] = []; 
} 
arrayAA[someStringValue].push(varB)

(Thanks to Ivar)

BertC
  • 2,243
  • 26
  • 33
  • 1
    Regarding your edit: It's more like `if (arrayAA[someStringValue] === undefined || arrayAA[someStringValue] === null) { arrayAA[someStringValue] = []; } arrayAA[someStringValue].push(varB)`. Your version doesn't push elements if the array doesn't exist. The `?==` variant always pushes the element, but if the array doesn't exist, it will create one first. – Ivar Jan 26 '23 at 10:35
  • 1
    Just a note: Your proposed alternative isn't actually the same. `!x` checks that `x` is "[falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)", where as that operator checks it's "[nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish)" (which is a subset of the possible falsy values) – DBS Jan 26 '23 at 10:35

1 Answers1

-3

It's a Nullish coalescing assignment (??=).

It will only assigns if the left operand is nullish (null or undefined).

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • 3
    @Normal I would imagine it's because there are multiple available duplicates, and some people are quite firmly against anyone answering duplicates. – DBS Jan 26 '23 at 09:55
  • 2
    It's a low effort answer to a low effort question that is a FAQ. It took less than a minute between the question being asked and a duplicate being found. – Quentin Jan 26 '23 at 09:58
  • 3
    Votes are to determine the usefulness of posts. Spreading information across Stack Overflow [is not useful](https://stackoverflow.com/help/duplicates). (And someone with 25k+ reputation should be aware of that.) – Ivar Jan 26 '23 at 09:59
  • Thank you Matthieu. I have rewritten that operand into 'normal' code with an IF-statement. (Edit the question because I can't add more answers). – BertC Jan 26 '23 at 10:33