# User Defined Functions

## Basic Syntax
**Note:** Name of user-defined function must have '$' as suffix
```vb
DEF FN functionName$(param1$, param2$, ...)
    ' Function body
    RETURN value
END DEF
```
Parameters must end with `$` too. A `#` name is a constant and cannot be a parameter:
```vb
DEF FN area$(w$, H#)   ' Error at line 1: DEF FN AREA$: expected a parameter name ending in $, got 'H#' - # names are constants and cannot be parameters
    RETURN w$ * H#
END DEF
```

## Important to remember

A user-defined function must always return a value, and BazzBasic always expects that value to be used — assigned to a variable or passed to a command like `PRINT`.

```vb
DEF FN double$(x$)
    RETURN x$ * 2
END DEF

PRINT FN double$(21)        ' ✓ OK - return value goes to PRINT
LET foo$ = FN double$(5)    ' ✓ OK - return value stored in foo$
FN double$(21)              ' ✗ ERROR - return value has nowhere to go
```

## Simple Function
```vb
DEF FN double$(x$)
    RETURN x$ * 2
END DEF

PRINT FN double$(21)    ' Output: 42
PRINT FN double$(5)     ' Output: 10
```

## Multiple Parameters
```vb
DEF FN add$(a$, b$)
    RETURN a$ + b$
END DEF

DEF FN multiply$(a$, b$)
    RETURN a$ * b$
END DEF

PRINT FN add$(3, 4)         ' Output: 7
PRINT FN multiply$(3, 4)    ' Output: 12
```
A call must pass exactly as many arguments as the function has parameters. `FN add$(3)` stops with `Error at line N: FN ADD$: expected 2 arguments, got 1`. This applies to functions from `.bb` libraries too.

## Array data as parameter
Arrays cannot be passed directly to functions. Instead, pass individual elements as values or whole array as JSON string.

### As single values
```vb
DIM a$
a$("name") = "Foo"
a$("age") = 19
a$(1) = 1

DEF FN func$(a$, b$, c$)
    PRINT a$
    PRINT b$
    PRINT c$
    RETURN 0
END DEF

LET b$ = FN func$(a$("name"), a$("age"), a$(1))
' Output:
' Foo
' 19
' 1
```

### As JSON
```vb
' ==================================================
' Example how to pass array to user-defined function
' Starting from ver. 1.2
' EkBass, public domain
' ==================================================

 ' User-defined functions
DEF FN ArrayAsParam$(data$)
    DIM array$

    LET count$= ASARRAY(array$, data$)
    LET daString$
        daString$ = array$("name") + "\n"
        daString$ = daString$ + array$("score") + "\n"
        daString$ = daString$ + array$("address,city") + "\n"
        daString$ = daString$ + array$("skills,0") + "\n"
        daString$ = daString$ + array$("skills,1") + "\n"

    RETURN daString$
END DEF

[inits]
    DIM player$
        player$("name") = "Alice"
        player$("score") = 9999
        player$("address,city") = "New York"
        player$("skills,0") = "JavaScript"
        player$("skills,1") = "Python"

    LET json$

[main]
    json$ = ASJSON(player$)
    ' json$ now: {"name":"Alice","score":9999,"address":{"city":"New York"},"skills":["JavaScript","Python"]}

[output]
    PRINT FN ArrayAsParam$(json$)
END

' Output:
' Alice
' 9999
' New York
' JavaScript
' Python
```

## String Functions
```vb
DEF FN greet$(name$)
    RETURN "Hello, " + name$ + "!"
END DEF

PRINT FN greet$("Alice")    ' Output: Hello, Alice!
```

## Functions with Logic
```vb
DEF FN max$(a$, b$)
    IF a$ > b$ THEN
        RETURN a$
    ELSE
        RETURN b$
    END IF
END DEF

DEF FN min$(a$, b$)
    IF a$ < b$ THEN
        RETURN a$
    ELSE
        RETURN b$
    END IF
END DEF

PRINT FN max$(10, 25)    ' Output: 25
PRINT FN min$(10, 25)    ' Output: 10
```

## Recursive Functions
Functions can call themselves:
```vb
DEF FN factorial$(n$)
    IF n$ <= 1 THEN
        RETURN 1
    END IF
    RETURN n$ * FN factorial$(n$ - 1)
END DEF

PRINT FN factorial$(5)    ' Output: 120
PRINT FN factorial$(10)   ' Output: 3628800
```


## Scope
User-defined functions have their own local scope that is completely isolated from the main program:

- Function parameters are local to the function
- Variables declared with `LET` inside a function are local to that function  
- Functions **cannot** access or modify global variables from the main program
- The same goes for arrays: global arrays are **not** visible inside a function. Pass an array as a JSON string with `ASJSON()` and rebuild it inside with `ASARRAY()`
- An array declared with `DIM` inside a function is local and starts empty on every call (and on every recursion level)
- Parameters are passed **by value** - changes to parameters don't affect the original variables
```vb
LET b$ = 100              ' Global variable
LET C# = "Foo"            ' Global constant
DEF FN test$(a$)          ' Parameter a$ is local
    LET b$ = 2            ' Local b$ (separate from global b$)
    PRINT C#              ' Global constants are available
    a$ = a$ * b$          ' Uses local a$ (100) and local b$ (2)
    RETURN a$             ' Returns 200
END DEF
```

**In this example:**
- The global `b$` has value 100
- When calling `FN test$(b$)`, the **value** 100 is passed to parameter `a$`
- Inside the function, a new **local** variable `b$` is created with value 2
- The local `b$` is completely separate from the global `b$`
- The function calculates `a$ * b$` = 100 × 2 = 200
- The global `b$` remains unchanged at 100


## Labels Inside Functions
Functions can have local labels for GOTO/GOSUB:

```vb
DEF FN countdown$(n$)
    [loop]
    IF n$ <= 0 THEN
        RETURN "Done!"
    END IF
    PRINT n$
    n$ = n$ - 1
    GOTO [loop]
END DEF

PRINT FN countdown$(5)
```

Output:
```
5
4
3
2
1
Done!
```

## Function Isolation
GOTO and GOSUB inside a function **cannot** jump outside the function:

```vb
[outside_label]
PRINT "Outside"

DEF FN broken$(x$)
    GOTO [outside_label]    ' ERROR! Label is outside of function
    RETURN x$
END DEF
```

This produces: `GOTO cannot jump outside function: outside_label`

This restriction ensures functions are self-contained and predictable.

## Practical Examples

### Is Even/Odd
```vb
DEF FN isEven$(n$)
    RETURN MOD(n$, 2) = 0
END DEF

DEF FN isOdd$(n$)
    RETURN MOD(n$, 2) = 1
END DEF

FOR i$ = 1 TO 5
    IF FN isEven$(i$) THEN
        PRINT i$; " is even"
    ELSE
        PRINT i$; " is odd"
    END IF
NEXT
```

## Order of code
Before code can call a user-created function, it must be loaded from the source code.

### Wrong
Code below causes error: _Error at line 2: Function not found: ADD$_
```vb
' incorrect way
PRINT FN ADD$(1, 2)

DEF FN ADD$(a$, b$)
	RETURN a$ + b$
END DEF
```

### Right
Code below is valid
```vb
' correct way
DEF FN ADD$(a$, b$)
	RETURN a$ + b$
END DEF

PRINT FN ADD$(1, 2)
```

## Tip

If you have several of your own functions, write them in their own file and include them in the code using _INCLUDE_ right at the beginning of your program.