Tag Archives: left

Powershell comparison: $null on the left

When I write powershell scripts, I always use below method to check whether variable is null or not.

if ($variable -eq $null) {
}

When I use VScode, VScode suggested me to put $null to left. Why?

Check below example:

$object = @(1, $null, 2, $null)

# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
	# -eq gets @($null, $null) which is evaluated to $true by if
	'This is called.'
}

# safe comparison with $null
if ($null -eq $object) {
	'This is not called.'
}

So, the right way to compare is always put $null on the left side.

if ($null-eq $variable) {
}