Variable Declarations

const

Syntax

const (varname[: type] | destructuring) = expression

Description

const name = 'John'

const declares the variable name as immutable reference. But the referenced value can be modified.

const names = ['John']
names.push('Jane')
// names: ['John', 'Jane']
// but
names = ['John']
// will through an error

Typing

If not type is provided, const will deduce the variable's type based on its value.

const name = 'John'
// type: String
const names: Array = []
// type: Array

The type of a variable declared with const can't be changed.

let

Syntax

let (varname[: type] | destructuring) = expression
let (varname | destructuring) := expression
let varname1[, varname2 ... [, varnamN]]

Description

let name = 'John'

let declares the variable name and it's rebindable.

let name = 'John'
name = 42
// no error

Typing

If a type is provided at the declaration of a variable, its type can't be changed.

let name: String = 'John'
name = 42
// throws a TypeException error

Auto-Typing

:= make the variable's type to be immutable. The type will be deduced from the initial value.

let name := 'John'
// type: String
name = 42
// throws a TypeException error

assignement

Like JavaScript, kaoscript can create variables with assignements:

name = 'John'

But unlike JavaScript, in kaoscript, those variables are created only inside the current block.

func foobar() {
x = 42
console.log(x)
}
foobar()
// 42
console.log(x)
// throw the ReferenceException error: "x" is not defined

no-undefined

You can disable the creation of variables via assignments, with the attribute #[rules(no-undefined)]

#![rules(no-undefined)]
func foobar() {
x = 42
// throw the ReferenceException error: "x" is not defined
console.log(x)
}