`let x` without assignment (`let x = 1`)

Example from Let Blocks

var1 = let x
       display(@isdefined x) #false
           for i in 1:5
               (i == 4) && (x = i; break)
           end
           x
       end

we see that x is undefined before the assigned in for block. However

var1 = let 
       display(@isdefined x) #false
           for i in 1:5
               (i == 4) && (x = i; break)
           end
           x
       end

change let x to let, an error is fired. What does let x do actually?

Edit: from topic:92211 (much thanks to stevengj for the hints)

The comma-delimited assignments in the “head” of the let statement behave differently from assignments in its body.

The behavior of let statements is like function definitions, where the head is like the argument list for a function with default values:

A variable without an assignment declares a new local variable in a let block but does not give it a value.

This was recently clarified in the docs: clarify `let x` without an assignment by stevengj · Pull Request #48122 · JuliaLang/julia · GitHub

See also the discussion here Syntax: How to write a cleaner code for many composed computations - #12 by uniment

4 Likes