Skip to content

Commit b927e39

Browse files
authored
Add note on variable scope, closes #1511
1 parent 517ecb0 commit b927e39

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

getting-started/case-cond-and-if.markdown

+27-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ iex> cond do
111111
"But this will"
112112
```
113113

114-
This is equivalent to `else if` clauses in many imperative languages (although used much less frequently here).
114+
This is equivalent to `else if` clauses in many imperative languages - although used less frequently in Elixir.
115115

116116
If all of the conditions return `nil` or `false`, an error (`CondClauseError`) is raised. For this reason, it may be necessary to add a final condition, equal to `true`, which will always match:
117117

@@ -165,6 +165,32 @@ iex> if nil do
165165
"This will"
166166
```
167167

168+
This is also a good opportunity to talk about variable scoping in Elixir. If any variable is declared or changed inside `if`, `case`, and friends, the declaration and change will only be visible inside the construct. For example:
169+
170+
```elixir
171+
iex> x = 1
172+
1
173+
iex> if true do
174+
...> x = x + 1
175+
...> end
176+
2
177+
iex> x
178+
1
179+
```
180+
181+
In said cases, if you want to change a value, you must return the value from the `if`:
182+
183+
```elixir
184+
iex> x = 1
185+
1
186+
iex> x = if true do
187+
...> x + 1
188+
...> else
189+
...> x
190+
...> end
191+
2
192+
```
193+
168194
> Note: An interesting note regarding `if/2` and `unless/2` is that they are implemented as macros in the language; they aren't special language constructs as they would be in many languages. You can check the documentation and the source of `if/2` in [the `Kernel` module docs](https://hexdocs.pm/elixir/Kernel.html). The `Kernel` module is also where operators like `+/2` and functions like `is_function/2` are defined, all automatically imported and available in your code by default.
169195
170196
## `do/end` blocks

0 commit comments

Comments
 (0)