Should $null be on the left side of the equality comparison? (-eq with arrays)

powershell

Solution

When performing comparison operations, PowerShell will evaluate the first operand the operation to determine if it is a collection or a scalar value. If it is a scalar, it will compare the operands to each other as whole objects.

2 -eq 1,2,$null,3
False

$null -eq 1,2,$null,3
False

4 -eq 1,2,$null,3
False

If it is a collection, it will iterate through the collection comparing each element to the second operand and return the value of the second operand if it finds a match.

1,2,$null,3 -eq 2
2

1,2,$null,3 -eq $null
<nothing appears, indicating returned value is $null>

1,2,3 -eq 4
<nothing appears, indicating returned value is $null>

The key difference between the second and third examples. Unless you know absolutely whether the second operand is always or never `$null`, you can't trust the output of the comparison operation.

On a side note, if both operands are collections, `-eq` returns `$null` in every case, because you can't use `-eq` to compare collections.

So to answer the question, it is generally good practice to put `$null` on the left side because when using `$null` in a comparison operation, it is assumed that you want to compare scalar values. If that assumption is wrong, then `$null` may be better placed on the opposite side, but it's not likely.

Contrarily, I always put `$null` on the right side because I write my code under the aforementioned assumption - that I am always comparing scalar values when `$null` is explicitly mentioned in the comparison operation. That way, when I get a non-boolean value returned, I know that I have not accessed my collection object properly in the equation. I have gotten caught in the trap, however, so my coding practices may be better served by changing my ways.

In conclusion, like any coding practice, it's a matter of opinion. Were I to teach PowerShell, I would teach this practice. However, I find it unlikely I will change my seditious ways.

Problem

Discussion with a colleague, should `$null` be on the left or right side of the check? Any examples of why this is important? ``` $abc = $null $null -eq $abc True $abc -eq $null True ``` All ok ``` $abc = 6,7,$null,8,9 $null -eq $abc False $abc -eq $null *No output* ``` Can someone explain what is happening when an array is compared?

Original source