Skip to content

Commit a4d1af0

Browse files
committed
Add section about variable scope
1 parent 580c414 commit a4d1af0

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

lib/elixir/lib/kernel.ex

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3935,6 +3935,26 @@ defmodule Kernel do
39353935
39363936
If you find yourself nesting conditionals inside conditionals,
39373937
consider using `cond/1`.
3938+
3939+
## Variables scope
3940+
3941+
Variables can be defined or rebound in `do`/`else` blocks, but these will not leak to the outer context:
3942+
3943+
x = 1
3944+
if x > 0 do
3945+
x = x + 1
3946+
IO.puts(x) # prints 2
3947+
end
3948+
x # 1
3949+
3950+
Variables can be defined in the condition as well, but they are available in the outer context:
3951+
3952+
fruits = %{oranges: 3}
3953+
if count = fruits[:apples] do
3954+
IO.puts(count + 1)
3955+
end
3956+
counts # nil
3957+
39383958
"""
39393959
defmacro if(condition, clauses) do
39403960
build_if(condition, clauses)

0 commit comments

Comments
 (0)