Variable Scopes
Variable scope is a fundamental concept in Elixir, referring to the area of code where a variable can be accessed or is valid. To better understand how variable scopes work in Elixir, let’s consider the following example using fruits.
defmodule FruitShop do
def fruit_count do
apples = 10 (1)
IO.puts("Apples in the shop: #{apples}")
basket_fruits() (2)
IO.puts("Apples in the shop: #{apples}") (4)
end
defp basket_fruits do
apples = 5 (3)
IO.puts("Apples in the basket: #{apples}")
end
end
| 1 | Here, we declare the number of apples in the shop as 10. |
| 2 | We then call the basket_fruits/0 function. |
| 3 | Inside the basket_fruits/0 function, we declare the count of apples in the basket as 5. |
| 4 | After coming back from the basket, we check the count of apples in the shop again. |
The output of calling FruitShop.fruit_count() would be:
Apples in the shop: 10
Apples in the basket: 5
Apples in the shop: 10
As you can see, the number of apples in the basket_fruits/0 function did not affect the number of apples in the fruit_count/0 function. This is because, although they have the same name (apples), they are in different scopes and, hence, are treated as completely different variables.