Your First Elixir Code

Go ahead and have a look at the installation instructions for setting up Elixir. Once you’re done, come back to this page.

Our First Elixir Program

It’s time to write your first Elixir program! Following a tradition that dates back to the 1970s, we’ll start by creating a program that prints “Hello, world!” to the screen. This simple program will help us verify that everything is set up correctly and introduce us to some basic Elixir concepts.

Let’s dive in! Open your favorite text editor and type the following code: Let’s try the same for Elixir. We’ll try out different ways to do it.

Option - 1: Scripting mode

Go ahead and type the following code in an IDE / Text Editor of your choice.

IO.puts("Hello, world!")

Save this file as hello_world.exs. Don’t worry too much about the .exs extension for now - we’ll explain that in a moment.

To run the program, open your terminal and type:

elixir hello_world.exs

The file type .exs indicates that it’s an Elixir script. You should see the following output printed on screen:

Hello, world!

Option - 2: Compilation

Elixir can be both compiled and interpreted. Compiled code is faster than interpreted code, and it can be run on the BEAM VM, which is what we’ll be working with in the coming lessons.

For compiling the code, we’ll write it in .ex files, which indicates to the elixir compiler that the file contains source code that should be compiled to make it runnable by the BEAM VM.

Let’s write some code and compile it:

defmodule HelloWorld do
  def hello do
    IO.puts("Hello, world!")
  end
end

Save the file as hello_world_123.ex. Now change to the directory where the file is saved and compile the file with the following command:

# Compile the file to be run on the BEAM VM
elixirc hello_world_123.ex

We should see a new file named Elixir.HelloWorld.beam in the same directory. This file contains the compiled bytecode for the program, which can be executed on the BEAM VM. If you’ve used languages like Java, this is similar to the .class file generated by the compiler.

To run the program, open a terminal in the current directory and start the iex shell by typing iex in your terminal / command prompt. Doing so will open an interactive Elixir shell, which will load all the compiled beam files in the current directory:

# Start the iex shell
iex

You should see an output similar to the following:

Erlang/OTP 26 [erts-14.1.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]

Interactive Elixir (1.15.7) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> HelloWorld.hello() # We can call the function in the iex shell.
Hello, world! # <-- The output is printed here due to calling IO.puts function
:ok # <-- The return value of IO.puts and thus, `HelloWorld.hello` is :ok