Elixir Scope

Learn the accessibility of data in top level, module, function and comprehension scope.

We'll cover the following

Elixir is lexically scoped. The basic unit of scoping is the function body. Variables defined in a function (including its parameters) are local to that function. In addition, modules define a scope for local variables, but these are accessible only at the top level of that module and not in functions defined in the module.

Types of scope

There are two types of scope in Elixir:

  • Top level scope

  • Function clause scope

There are a number of constructs that create new scope:

  • Modules and module-like structures: defmodule, defprotocol
  • Functions: fn, def, defp
  • Comprehensions: for,do
  • Try block bodies

Most of the time, user code in Elixir is structured in the following way. At the top level, we define modules. Each module contains a number of attributes and function clauses. Inside a function clause, there can be an arbitrary number of expressions, including control flow constructs like case, if, or try.

Get hands-on with 1200+ tech skills courses.