Functions
Functions are declared using the fn keyword and terminated with end. They are first-class citizen objects in Djazair.
Standard Declaration
fn calculateSum(a, b)
return a + b
end
print(calculateSum(10, 20)) # => 30
Default Arguments
Djazair allows function parameters to have default values, which are evaluated if the argument is omitted:
fn greet(name = "Guest", prefix = "Hello")
return "${prefix}, ${name}!"
end
print(greet()) # => Hello, Guest!
print(greet("Riad", "Hi")) # => Hi, Riad!
Rest Parameters
Collect variable amounts of arguments into a single array using the ... syntax prefix:
fn printLog(level, ...messages)
print("[${level}]", messages.join(" "))
end
printLog("INFO", "Server started on", "port", 8080)
# Output => [INFO] Server started on port 8080
Arrow Functions & Expressions
Write compact lambdas using the arrow symbol (=>):
let square = fn(x) => x * x
print(square(4)) # => 16
# Named function with arrow syntax
fn double(x) => x * 2
print(double(5)) # => 10
Closures
Functions capture their surrounding lexical scope. Inner functions can access and modify outer variables:
fn makeCounter()
let count = 0
return fn()
count += 1
return count
end
end
let c = makeCounter()
print(c()) # => 1
print(c()) # => 2
print(c()) # => 3
Higher-Order Functions
Pass functions to array methods for transformation, filtering, and reduction:
let nums = [1, 2, 3, 4, 5]
print(nums.map(fn(x) => x * 2)) # => [2, 4, 6, 8, 10]
print(nums.filter(fn(x) => x > 2)) # => [3, 4, 5]
print(nums.reduce(fn(a, x) => a + x, 0)) # => 15
# Method chaining
let result = [1, 2, 3, 4, 5]
.filter(fn(x) => x % 2 == 0)
.map(fn(x) => x * 10)
.reduce(fn(acc, x) => acc + x, 0)
print(result) # => 60
Async Functions
Declare asynchronous functions using async fn. They return coroutines that can be awaited:
async fn fetchData()
# Simulate async work
return 42
end
let task = fetchData()
let result = await task
print(result) # => 42