Control flow, loops and comprehensions

Branch with if and the ternary operator, loop over ranges and pairs, and express transformations as comprehensions or broadcasts.

Branching

function grade(score)
    if score >= 90
        "A"
    elseif score >= 80
        "B"
    elseif score >= 70
        "C"
    else
        "F"
    end
end

# the ternary operator: a value, not a statement
status = score >= 50 ? "pass" : "fail"

# short-circuit evaluation returns one of its operands
name = isempty(input) || input
value = isempty(input) && "default"
  • if is an expression that returns a value; the last expression of the chosen branch is the result.
  • Conditions must be Bool. There is no truthiness of numbers or strings, which removes a whole class of C-style bugs.
  • && and || require Bool operands, so use if when you want a value from a non-boolean test.

Loops

total = 0
for i in 1:10
    total += i
end

for (i, name) in enumerate(["a", "b", "c"])
    println(i, " ", name)
end

for (x, y) in zip(1:3, 10:12)
    println(x + y)
end

i = 0
while i < 5
    global i += 1          # assignment to an outer name in a script needs global
    i == 3 && continue
    i == 4 && break
end
RangeMeaning
1:10Inclusive, step 1
1:2:9Inclusive start, step 2, stops at 9
1.0:0.5:2.0Floating-point range, use range for a count
range(0, 1, length = 11)Exactly eleven evenly spaced points
LinRange(0, 1, 11)Same, without floating-point accumulation error

Use length = n or LinRange rather than computing a step, because accumulating a floating-point step produces inexact endpoints and sometimes one element too many or too few.

Comprehensions and broadcasting

squares = [x^2 for x in 1:10]
evens   = [x for x in 1:20 if iseven(x)]
matrix  = [i * j for i in 1:3, j in 1:3]        # two indices build a matrix

# broadcasting: apply a function element-wise with a dot
v = [1.0, 2.0, 3.0]
sqrt.(v)
v .+ 1
v .^ 2

# fusion: the whole expression becomes one loop, with no temporaries
fused = sin.(v) .^ 2 .+ cos.(v) .^ 2

# @. turns every operator and call in the expression into a broadcast
results = @. exp(-v / 2)
⚠️
A loop written at the top level of a script runs in global scope, where every variable has an unknown type and performance can be fifty times worse than the same loop inside a function. Wrap hot loops in a function, or use let, before you conclude that Julia is slow.

FAQ

Should I write a comprehension or an explicit loop?
A comprehension when the body is a pure expression over a collection, a loop when the body has multiple statements, early exits or accumulation across iterations.
What does the dot in v .+ 1 do differently from v + 1?
The dotted form applies the operation element-wise and fuses with neighbouring dotted calls. An undotted + on two vectors is a method error unless the operation is genuinely defined for vectors.

Arrays and broadcasting in depth Syntax and the type system

Last refreshed 2026-09-18.