GiavaScript / docs

Reference

GiavaScript documentation

GiavaScript is a small, cross-platform JavaScript runtime. It implements a curated subset of JavaScript, so this reference describes GiavaScript behavior only.

Getting Started

Install with Homebrew on macOS or Linux:

brew tap GiavaScript/giavascript && brew install giavascript

Update an existing installation:

brew update && brew upgrade giavascript

Run a file with gs path/to/program.js, or start the REPL with gs. Leave the REPL with :quit. An empty file is an error. Runtime errors go to standard error; an Error: message gives the CLI an exit status of 1.

var name = "GiavaScript";
console.log(`Hello, ${name}`); // stdout: Hello, GiavaScript

Language Basics

Use var declarations, assignment, compound assignment, postfix ++/--, numbers, strings, booleans, null, undefined, arrays, objects, functions, dates, regular expressions, and errors. Property access uses dot or brackets. Statements on separate lines do not need semicolons. Local files can be evaluated with import "path/to/file.js".

Supported operators include arithmetic, bitwise, comparisons, strict and coercive equality, logical operators, ternaries, unary +, typeof, and void. ==/!= coerce; ===/!== do not. && and || return an operand and short-circuit. Falsy values are false, 0, 0.0, "", null, and undefined; arrays and objects are truthy.

var total = 4;
total += 3;
total; // 7

var copy = [...[1, 2], 3];
copy; // [1, 2, 3]

var user = {name: "Ada"};
({role: "admin", ...user}).name; // Ada

typeof missing; // undefined
0 || "fallback"; // fallback

Functions

Declarations, expressions, named expressions, arrows, implicit returns, block bodies, recursion, default parameters, rest parameters, and call-argument spread are supported. Functions are first-class and close over outer variables. Non-callback user calls require every fixed parameter; rest must be last. A function without return produces undefined.

function add(left, right) {
  return left + right;
}
add(20, 22); // 42

var double = value => value * 2;
double(21); // 42

function collect(first, ...rest) { return rest; }
collect(1, 2, 3); // [2, 3]

function sum(a, b, c) { return a + b + c; }
sum(...[10, 20, 12]); // 42

Control Flow

Use if/else, C-style for, for...of, for...in, while, do...while, switch, break, continue, throw, try, catch, finally, and return. for...of iterates arrays and strings; for...in iterates object keys. Switch cases use strict matching and fall through until break. finally always runs and may override a return or thrown value.

var sum = 0;
for (var i = 1; i <= 3; i++) sum += i;
sum; // 6

var label = "";
switch (2) {
  case 1: label = "one"; break;
  case 2: label = "two"; break;
  default: label = "other";
}
label; // two

Values and Collections

Arrays support indexing, mutable length, and array methods listed below. Objects support own string-keyed properties, dot/bracket access, and spread. Array and object spread ignore non-array and non-object values.

Global APIs

console.log(...values)

Writes space-separated values to stdout. Returns undefined.

console.log("answer:", 42); // stdout: answer: 42

console.warn(...values)

Writes to stderr. Returns undefined.

console.warn("careful"); // stderr: careful

console.error(...values)

Writes to stderr. Returns undefined.

console.error("failed"); // stderr: failed

parseInt(value, radix?)

Parses an integer prefix and returns a number or NaN. Radix is 0 or 2 through 36.

parseInt("11", 2); // 3

parseFloat(value)

Parses a floating-point prefix and returns a number, Infinity, or NaN.

parseFloat("3.14px"); // 3.14

isNaN(value)

Coerces to a number, then tests for NaN.

isNaN("nope"); // true

readLine()

Reads one stdin line without its newline. Returns "" at EOF.

readLine(); // string from stdin

fetch(url, options?)

Performs a synchronous HTTP request. Returns {status, ok, headers, text, json}, not a Promise.

fetch("https://example.com").status; // HTTP status number

options supports method, headers, and body. text() returns the body; json() parses it or raises an error.

String

Strings have a read-only length. Indexes are integer character indexes.

String.fromCharCode(...codeUnits) builds from UTF-16 units. at(index), charAt(index), charCodeAt(index), codePointAt(index) read characters. concat(suffix), startsWith(value), endsWith(value), includes(value), indexOf(value), lastIndexOf(value) search or combine text. match(pattern), matchAll(pattern), search(pattern), replace(search, replacement), and replaceAll(search, replacement) use strings or regexes. padStart(length, fill?), padEnd(length, fill?), repeat(count), slice(start, end?), split(separator, limit?), and substring(start, end?) return transformed text. Casing: toLowerCase(), toUpperCase(), toLocaleLowerCase(), toLocaleUpperCase(). Whitespace: trim(), trimStart(), trimEnd(). Conversion: toString(), valueOf(), isWellFormed(), toWellFormed(), localeCompare(other).
"GiavaScript".includes("Script"); // true
"7".padStart(3, "0"); // 007
"a-a".replaceAll("a", "b"); // b-b

Array

Static APIs: Array.isArray(value), Array.of(...values), Array.from(arrayOrStringOrArrayLike). Instance APIs: at(index), concat(...values), copyWithin(target, start, end?), entries(), keys(), values(), every(fn), some(fn), filter(fn), find(fn), findIndex(fn), findLast(fn), findLastIndex(fn), fill(value, start?, end?), flat(depth?), flatMap(fn), forEach(fn), includes(value, fromIndex?), indexOf(value, fromIndex?), lastIndexOf(value, fromIndex?), join(separator?), map(fn), pop(), push(...values), reduce(fn, initial?), reduceRight(fn, initial?), reverse(), shift(), unshift(...values), slice(start?, end?), sort(), splice(start, deleteCount?, ...items), and toString(). Callbacks receive (value, index, array); reducers receive (accumulator, value, index, array). Mutating methods return the array or new length; forEach returns undefined.

[1, 2, 3].map(x => x * 2); // [2, 4, 6]
[1, 2, 3].reduce((sum, x) => sum + x, 0); // 6

Object, Number, and Boolean

Object.assign(target, ...sources) copies properties and returns the target. Object.hasOwn(object, property) returns a boolean. Object.keys(object), Object.values(object), and Object.entries(object) return arrays. object.toString(), number.toString(), and boolean.toString() return strings. Number.isInteger(value), Number.isFinite(value), and Number.isNaN(value) return booleans; Number methods do not coerce.

Object.keys({a: 1, b: 2}); // ["a", "b"]
Number.isInteger(42); // true

Math

Constants: E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2. Unary numeric methods take one number and return a number: abs, sqrt, acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, clz32, cos, cosh, exp, expm1, f16round, floor, fround, log, log10, log1p, log2, round, sign, sin, sinh, tan, tanh, trunc. Also: atan2(y, x), hypot(...values), imul(left, right), max(...values), min(...values), pow(base, exponent), random(), sumPrecise(...values). Numeric arguments must be numbers. hypot() is 0; max() is -Infinity; min() is Infinity.

Math.sqrt(9); // 3
Math.max(3, 7, 4); // 7
Math.pow(2, 5); // 32
Math.imul(2, 21); // 42
Math.random(); // pseudo-random number in [0, 1)

Date and RegExp

Date.now() returns the current UTC Unix timestamp. new Date() takes no arguments; date.getTime() returns its timestamp and date.toString() returns a UTC ISO-like string. Regex literals use /pattern/flags; flags are g, i, m, s, and u. new RegExp(patternOrRegex, flags?) constructs one. Properties are source, flags, global, ignoreCase, multiline, dotAll, and unicode. test(value) returns a boolean, exec(value) returns a match array or null, and toString() returns literal-style text.

/\d+/.test("a42"); // true
/hello/gi.flags; // gi

JSON and Errors

JSON.parse(text) returns a parsed value and requires one string. JSON.stringify(value) returns a JSON string or undefined and requires one argument. Top-level undefined, functions, RegExp, and Error values return undefined; unsupported object properties are omitted, array values become null, non-finite numbers become null, and circular arrays or objects raise an error.

JSON.parse('{"answer":42}').answer; // 42
JSON.stringify({answer: 42}); // {"answer":42}

var error = new TypeError("expected a number");
error.name; // TypeError
error.toString(); // TypeError: expected a number

Constructors are new Error(message?), new TypeError(message?), new ReferenceError(message?), and new SyntaxError(message?). Each has message, name, stack, and toString().

File, Process, and Network

Host-integrated APIs depend on the machine and its permissions.

File.read(path) returns UTF-8 text. File.readLines(path) returns lines with CRLF normalized to LF. File.write(path, content) and File.append(path, content) return undefined. process.argv is the argument array; process.env is a read-only environment snapshot. process.exit(code?) exits with a numeric status, default 0. process.run(command, args?) synchronously returns {stdout, stderr, status}. fetch(url, options?) is the synchronous HTTP API described above.

File.write("out.txt", "hello"); // undefined
process.run("echo", ["hello"]).stdout; // hello followed by newline

Compatibility

GiavaScript is a curated runtime, not an ECMAScript-compliant browser or Node.js environment. These are not available:

  • let and const
  • Browser DOM APIs
  • print() and len()
  • Array.fromAsync, Array.toReversed, Array.toSorted, Array.toSpliced, Array.with, Array.toLocaleString
  • String.substr

There are no promises or browser APIs. Use only the APIs documented here.