logo

How to Write Conditional Statements Concisely in Julia 📂Julia

How to Write Conditional Statements Concisely in Julia

Overview

In Julia, <condition> && <statement> executes <statement> when <condition> is true. As a function, it returns the result of <statement> if true, and if false, <statement> is not even evaluated.

While it allows writing code efficiently and concisely, it may reduce readability. Moreover, even if you don’t use it frequently, you should understand it to read the code written by others. Without any context, encountering such syntax can be utterly incomprehensible.

See Also

Code

Basic Example

▷code1◁

Since 2 is even, push!(num, 2) is evaluated, and 2 is added to the empty array num.

Return

▷code2◁

&& acts as a function too, thus can return some value. Here, check is considered to have received check = push!(num, 4) as a return.

▷code3◁

On the other hand, if <statement> is false, it is not evaluated and && itself returns false.

Negation

▷code4◁

Use || instead of &&.

Complete Code

▷code5◁

Environment

  • OS: Windows
  • julia: v1.6.3