DEV Community

Cover image for Conditional assignment ( ||= )
Merdan Durdyyev
Merdan Durdyyev

Posted on

Conditional assignment ( ||= )

Intro

Conditional assignment operator, otherwise called "or-equals", is widely used in almost all modern programming languages. It acts as a combination of two separate operators, which are "||" that we call "or" operator, and another one "=", an assignment operator.

Ruby example (Ordinary "||" usage)

To illustrate the difference, let's just take a look at couple of examples using regular "||" operator. We will print the "comments" list variable in both cases.
In first case it will return empty list, because previously it had no value (it had 'nil' as a value) and as an assignment value it gets the value on the right, that is an empty list.

# Example-1
comments = nil
comments = comments || []
puts comments  # returns [], empty list
Enter fullscreen mode Exit fullscreen mode

In the second example, because the "comments" variable already has a value, i.e. is not previously empty, it just returns its result that stands as a first value in assignment.

# Example-2
comments = ["First comment"]
comments = comments || []
puts comments  # returns ["First comment"]
Enter fullscreen mode Exit fullscreen mode

Ruby example (Conditional assignment "||=" usage)

This time, we will illustrate usage of "||=" conditional assignment operator. We will print the "comments" list variable in both cases, as in the section above.
In first case it will return empty list, because previously it had no value (it had 'nil' as a value) and as an assignment value it gets the value on the right, that is an empty list.

# Example-1
comments = nil
comments ||= []
puts comments  # returns [], empty list
Enter fullscreen mode Exit fullscreen mode

In the second example, because the "comments" variable already has a value, i.e. is not previously empty, it just gets its previous value in assignment.

# Example-2
comments = ["First comment"]
comments ||= []
puts comments  # returns ["First comment"]
Enter fullscreen mode Exit fullscreen mode

Even shorter

It actually lets us shorten a longer conditional checking and assignment to one line. Let's look at an example that gets "comments" list variable.

module Commentable
   def comments
      if @comments
         @comments
      else
         @comments = []
      end
   end
end
Enter fullscreen mode Exit fullscreen mode

And here we shorten the content of the function to one line.

module Commentable
   def comments
      @comments ||= []
   end
end
Enter fullscreen mode Exit fullscreen mode

And this was a great example of how we can shrink multiline checking and assignment operation into just one single line.

Examples above were demonstrated using Ruby PL but conditional assignment operator can be used in other languages like Javascript, Python and many others as well. So go on experimenting...

Top comments (0)