Lesson 2
Understanding Variables in Elixir
Understanding Variables in Elixir

Welcome back! After learning how to print output to the console, it’s time to dive into another fundamental concept in Elixir: variables. Variables are the building blocks for storing and manipulating data in any programming language. They allow you to keep track of information and use it throughout your programs.

In this lesson, we will explore how to define and use variables in Elixir. This will set a strong foundation for more complex operations you will encounter later.

What You'll Learn

In this lesson, you’ll learn:

  1. How to assign values to variables
  2. How to concatenate strings
  3. How to use variables within strings using string interpolation

Here’s a quick preview of what you’ll be working with:

Elixir
1first_name = "Alice" 2last_name = "Smith" 3full_name = first_name <> " " <> last_name 4age = 30 5IO.puts "The user #{full_name} is #{age} years old."

Let’s break this down step by step. First, we assign the value "Alice" to first_name and "Smith" to last_name. By using the <> operator, we concatenate these two strings with a space in between to create a full_name. Then we assign the number 30 to the variable age. Finally, we use IO.puts to print a message that includes our variables.

Notice how we use the #{} syntax to embed variables within a string. This is called string interpolation and is a common technique in Elixir to include variables in strings. Thus, the output of this code will be:

Plain text
1The user Alice Smith is 30 years old.
Why It Matters

Understanding and working with variables is critical because:

  1. Data Storage: Variables allow you to store information that your program can use and manipulate.
  2. Code Reusability: By using variables, you can write more modular and flexible code.
  3. Enhanced Readability: Well-named variables make your code easier to read and understand.

Imagine you're building a user profile feature in an application. You need to store and manage information like the user’s name and age. Variables make it straightforward to handle this data efficiently.

Excited to put it into practice? Let’s move on to the practice section and start working with variables in Elixir!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.