$null on the left or right side.

Welcome Forums General PowerShell Q&A $null on the left or right side.

This topic contains 3 replies, has 4 voices, and was last updated by

Senior Moderator
1 month, 3 weeks ago.

  • Author
  • #168694

    Topics: 8
    Replies: 8
    Points: 90
    Rank: Member

    I have noticed to warning in PowerShell Tools for Visual Studio, when I write something like this:

    if($MyVar -eq $null)

    that $null should be on left side only. And I decided to do small experiment:

    if (@() -eq $null) { 'true' }else { 'false' }
    if (@() -ne $null) { 'true' }else { 'false' }
    if ($null -eq @()) { 'true' }else { 'false' }
    if ($null -ne @()) { 'true' }else { 'false' }
    If $null on the right side – the first two expressions return 'false' both. But, when null on the left side (last two expressions) – I've got 'false' and 'true'.
    May somebody to explain in details this behavior ?
  • #168709

    Topics: 37
    Replies: 155
    Points: 479
    Helping Hand
    Rank: Contributor

    I get the same result from both, that  I'd expect....but I also have read that $Null should be on left....$null -eq $MyVar

    $MyVar = $null
    $something = "me"
    if ($MyVar -eq $null) { 'true' }else { 'false' }
    if ($MyVar -ne $null) { 'true' }else { 'false' }
    if ($something -eq $null) { 'true' }else { 'false' }
    if ($something -ne $null) { 'true' }else { 'false' }
    if ($null -eq $MyVar) { 'true' }else { 'false' }
    if ($null -ne $MyVar) { 'true' }else { 'false' }
    if ($null -eq $something) { 'true' }else { 'false' }
    if ($null -ne $something) { 'true' }else { 'false' }


  • #168730

    Topics: 9
    Replies: 423
    Points: 676
    Helping Hand
    Rank: Major Contributor
    5 -eq $null   # False
    @() -eq $null # $null
    $null -eq @() # False
    $null -eq 5   # False

    does it make sense now!?

    In other words, when $null on the left side the -eq or -ne operators will cause the expression to evaluate to True or False, whereas when $null is on the right side the expression will evaluate to $null or True or False. When the expression evaluates to $null, the 'else' branch of the 'if' statement is invoked.

  • #168853

    Senior Moderator
    Topics: 8
    Replies: 1041
    Points: 3,440
    Helping Hand
    Rank: Community Hero

You must be logged in to reply to this topic.