Variables and Constants
Variable Declaration
Variables are used to store values. The data type of a variable is automatically determined based on the value assigned to it. Therefore, variables in JARU can store values of different types, such as integers, floats, text strings, lists, dictionaries, arrays, etc.
The keyword var in JARU is used for variable declaration. This is one of the ways to create a variable in the language, along with const.
When using var to declare a variable, it is assigned in the function scope or in the global scope. If a variable is declared inside a function, it can only be accessed within that function. If declared outside any function, it's considered a global variable and can be accessed from anywhere in the code.
Variable declaration with var is done as follows:
var variable = 5
In this example, the variable variable has been declared and assigned the value 5. To assign a value to a variable, use the = symbol followed by the value you want to assign.
It's also possible to declare a variable with var without assigning an initial value. In this case, its value will be 0.
var variable
print(variable) // Prints "0"
As we've seen, in JARU variables automatically acquire the type when assigning a value to them. That is, it's not necessary to specify the variable type at the time of declaration.
Let's look at some examples:
// Declare a variable with a numeric value
var number = 5
// Declare a variable with a text string value
var name = "John"
// Declare a variable with a list value
var list = ["apple", "pear", "banana"]
// Declare a variable with a map value
var map = {name: "John", age: 25}
// Declare a variable with an empty array value
var array[10][20]
Constants
The keyword const is used to declare a variable as a constant. This means that the variable's value cannot be changed once it has been assigned. The compiler will generate an error if you try to change the value of a variable declared as const. This is useful for ensuring the immutability of important values in a program and for preventing accidental errors.
In JARU, constants are declared using the keyword const at the beginning of the declaration. Once a value has been assigned to a constant, it cannot be changed. If you try to assign a new value to a constant, a runtime error will be generated.
const myPI = 3.14
print(myPI) // shows 3.14
myPI = 3.15 // generates an error
If a constant refers to an object, list, map, or array, the value of that constant cannot be changed, but the values inside the object, list, map, or array can be changed.
println(person["name"]) // shows "Jon" with a line break
person["name"] = "Raquel" // correct assignment
person = { "name": "Steve" } // generates an error
The value of a constant cannot be changed once assigned, but if the constant is an object or array, the values inside that object or array can be changed.