What are the basic operators in Elixir?

Elixir is a concurrent, functional programming language designed to maintain and scale applications. Today, as an introduction to Elixir, you will learn about the basic operators that this programming language offers.

Basic operators

+ - Adds two numbers

- - Subtracts second number from first number

* - Multiplies two numbers

/ - Divides two numbers

rem - Gets the remainder on division

a = 10
b = 5
#Addition
IO.puts(to_string(a+b))
#Subtraction
IO.puts(to_string(a-b))
#Multiplication
IO.puts(to_string(a*b))
#Division
IO.puts(to_string(a/b))
#Modulo
IO.puts(to_string(rem(a,b)))

The code will create the following output:

15
5
50
2
0

Logical operators

or, and, and not are strictly boolean operators, which means that they expect their arguments to be a boolean value.

or - Checks if either value is truthy. If neither value is truthy, it returns false

and - Returns true if both values are truthy. Else it returns false

not - Unary operator that inverts the input value

Note: or and and are short-circuit operators, which means that they will only execute the right side if the left side is not enough to determine the return value.

true and true
> true

false or true
>true

||, && and ! accept any value type. For these operators, all values will return true except false and nil.

|| - Same functionality as or, but does not expect boolean for either argument

&& - Same functionality as and, but does not expect boolean for either argument

! - Same functionality as not, but does not expect boolean for either argument

5 || true
> 5

false || 13
> 13

nil && 17
> nil

true && 12
> 12

Comparison operators

== - Checks if values are equal (type casts values if they are not the same type)

!= - Checks if values are not equal

=== - Check if values have the same data type and the same values

!== - Checks if values are of the same data type and have different values

> - Checks if the value on the left is greater than the value on the right

< - Checks if the value on the right is greater than the value on the left

>= - Checks if the value on the left is greater than or equal to the value on the right

<= - Checks if the value on the right is greater than or equal to the value on the left

2 == 2
> true

2 != 4
> true

1 <= 2
> true

5 == 5.0
> true

5 === 5.0
> false

Other operators

Elixir offers ++ and -- to manipulate lists

++ - Concatenates two lists into one list

-- - Removes elements from a list

[1, 2, 6] ++ [7, 10, 15]
> [1, 2, 6, 7, 10, 15]

[1, 2, 6, 9] -- [6]
> [1, 2, 9]

<> - Concatenates two strings

"Hel" <> "lo"
> "Hello"

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved