[Elixir] How do I use conditional statements (if-else) in Elixir?

In Elixir, you can use conditional statements (if-else) to control the flow of your program based on certain conditions. Here's how you can use if-else statements in Elixir:

  1. Basic if-else statement:
1if condition do
2  # code to execute if the condition is true
3else
4  # code to execute if the condition is false
5end
  1. if-else with multiple conditions:
1if condition1 do
2  # code to execute if condition1 is true
3elsif condition2 do
4  # code to execute if condition2 is true
5else
6  # code to execute if both conditions are false
7end
  1. if-else as an expression:
1result = if condition do
2  # code to execute if the condition is true
3else
4  # code to execute if the condition is false
5end

In this case, the value of result will be the value of the executed block.

  1. Using guards with if-else:
1if condition when guard do
2  # code to execute if the condition is true and the guard matches
3else
4  # code to execute if the condition is false or the guard doesn't match
5end
  1. if-else with boolean logic: Elixir also supports boolean operators like and, or, and not for more complex conditional statements.
1if condition1 and condition2 do
2  # code to execute if both condition1 and condition2 are true
3else
4  # code to execute if either condition1 or condition2 is false
5end

Remember to replace condition with the actual condition you want to check in your code.