Integers
Integer types
Boa supports the following integer types:
| Type | Size (in bytes) | Signed ? | Minimum value | Maximum value |
|---|---|---|---|---|
u8 | 1 | No | 0 | 255 |
u16 | 2 | No | 0 | 65535 |
u32 | 4 | No | 0 | 4294967295 |
u64 | 8 | No | 0 | 18446744073709551615 |
i8 | 1 | Yes | -128 | 127 |
i16 | 2 | Yes | -32768 | 32767 |
i32 | 4 | Yes | -2147483648 | 2147483647 |
i64 | 8 | Yes | -9223372036854775808 | 9223372036854775807 |
Signed integers encoding
Boa's signed integers (i8, i16, i32, i64) are guaranteed to be encoded in 2's complement.
Integer literals
Integers in Boa can be written in the following bases:
- Base 2, with the
0bprefix - Base 8, with the
0oprefix - Base 16, with the
0xprefix.
let base_2 = 0b10000000
let base_8 = 0o200
let base_16 = 0x80The "post" prefix" part of an integer literal can contain _ (but cannot start with one), to improve legibility:
let one_billion = 1_000_000_000Integer literals and type inference
When creating a variable storing an integer without any type annotation, Boa will, in the following order:
- Assume it is a
i32if the value fits inside ai32 - Assume it is a
i64if the value fits inside ai64 - Assume it is a
u64if the value fits inside au64 - Raise a compilation error.
The following example illustrates this behavior:
let a = 12 // 12 fits into an i32, so a is an i32
let b = 2147483648 // b is too big for an i32 but fits in an i64 so it is an i64
let c = 9223372036854775808 // c is too big for an i64 but fits in an u64 so it is an u64
let d = 18446744073709551616 // d is too big for an u64 so a compilation error is raisedIf the type of the variable is specified and the value does not fit inside it, a compilation error is directly raised:
let a: u8 = 256 // compilation error because 256 is too big to fit in an u8Integer literals suffixes
It is possible to bypass the behavior defined in the previous section by adding a suffix to an integer literal to specify its type:
let a = 12i8 // 'a' is an i8 but would have been a i32 without the suffix
let b = 0u64 // 'b' is an u64 but would have been a i32 without the suffixAn integer literal defined with an incompatible suffix triggers a compilation error:
let a = 65535u8 // 65535 cannot fit in an u8, so a compilation error is triggeredIf type type of the variable is precised and an integer suffix is present, they must correspond to the same type or a compilation error is triggered:
let a: i32 = 8u64 // a's type is defined as i32 but the integer literal is defined as an u64. Boa cannot guess which one is correct, so a compilation error is triggered.