When we talk about functions in Imba, we refer to anonymous / inline functions declared with the
# defining a function
const square = do(num) num * num
# inside an object
const util =
upcase: do(str) str.toUpperCase!
downcase: do(str) str.toLowerCase!
Function scopes are selfless, meaning that
Defining a function does not execute it. Defining it simply names the function and specifies what to do when the function is called. Accessing a function does not execute it either. If an object has a property
When you call a function with arguments, parenthesis are optional.
# the following expressions are equivalent
console.log('hello')
console.log 'hello'
If you want to call a function without arguments, you have two options. Either with an empty pair of parenthesis, or with a
# the following expressions are equivalent
Math.random()
Math.random!
Many functions expect another function as an argument. These are often referred to as callbacks. To take a classic example,
Since this is a common pattern, inline anonymous functions can be passed in
[1,2,3].map do(item)
item * 2 # [2,4,6]
The convention is usually to take the callback as the last argument, but not always.
setTimeout((do
console.log 'waited!'
[1,2,3].reduce((do(sum,value)
sum + value
),0)
),1500) # looks pretty messy
When functions expect callbacks as their first (or not-last) argument, you can use
setTimeout(&,1500) do
console.log 'waited!'
[1,2,3].reduce(&,0) do(sum, value)
sum + value
You can refer to positional arguments from within functions with
[1,2,3,4,5].filter do $1 > 3