API Reference

Complete transpilation coverage for JavaScriptTarget.jl. This page documents every supported operation, type mapping, and compilation pattern. For a quick overview, see the Getting Started guide.

Core API

compile(f, arg_types; kwargs...)

Transpile a Julia function to JavaScript. Returns a JSOutput with .js, .ts, and .exports fields.

import JavaScriptTarget as JST

f(x::Int32) = x * x + 1
result = JST.compile(f, (Int32,))

println(result.js)       # JavaScript code
println(result.exports)  # ["f"]

Use optimize=false for functions that build arrays or use broadcasting on constructed arrays.

compile_module(functions; kwargs...)

Transpile multiple functions into a single JS module with shared runtime helpers.

result = JST.compile_module([
    (add, (Int32, Int32)),
    (mul, (Float64, Float64))
])

Transpilation Coverage

Everything below is fully transpiled from Julia to JavaScript. Integer operations use |0 to maintain 32-bit semantics.

Types

JuliaJavaScript
Int32, Int64number (integer ops use |0)
Float64number
Stringstring
Boolboolean
Nothingnull
struct / mutable structES6 class
TupleArray

Arithmetic & Comparison

JuliaJavaScript
+, -, *, /, %Same (integers use |0)
<, <=, >, >=, ==, !=<, <=, >, >=, ===, !==
&, |, ⊻, <<, >>, >>>Bitwise ops
div(a, b)jl_div(a, b) — truncating
fld(a, b)jl_fld(a, b) — floor division
mod(a, b)jl_mod(a, b) — sign of b
cld(a, b)jl_cld(a, b) — ceiling division
f(a::Int32, b::Int32) = a * b + 1
# → function f(a, b) { return (Math.imul(a, b) + 1) | 0; }

Math

JuliaJavaScript
sin, cos, tan, asin, acos, atanMath.sin, Math.cos, etc.
exp, log, log2, log10Math.exp, Math.log, etc.
sqrt, abs, min, maxMath.sqrt, Math.abs, etc.
floor, ceil, round, trunc, signMath.floor, Math.ceil, etc.
hypot, atan2Math.hypot, Math.atan2
copysign(a, b)jl_copysign(a, b)
f(x::Float64) = sin(x) * exp(-x) + sqrt(abs(x))
# → Math.sin(x) * Math.exp(-x) + Math.sqrt(Math.abs(x))

1D Arrays

JuliaJavaScript
Vector{T}, T[]Array
push!, pop!, append!.push(), .pop(), .push(...other)
length, getindex, setindex!.length, [i-1], [i-1] = v
copy, reverse, empty!.slice(), [...a].reverse(), .length=0
deleteat!.splice(i-1, 1)
sort (with by=, rev=).slice().sort(compareFn)
in / ∈.includes()
function process(arr::Vector{Int32})::Vector{Int32}
    filtered = filter(x -> x > 0, arr)
    return sort(filtered; rev=true)
end
# → arr.filter(x => x > 0).slice().sort((a, b) => b - a)

ND Arrays

Multi-dimensional arrays transpile to nested JavaScript arrays — the native format for JS libraries like Plotly, D3, and TensorFlow.js.

JuliaJavaScript
zeros(m,n), ones(m,n), fill(v,m,n)Nested arrays: [[0,0],[0,0]]
A[i,j], A[i,j,k]A[i-1][j-1], A[i-1][j-1][k-1]
A[i,j] = valA[i-1][j-1] = val
size(A), size(A,d)[A.length, A[0].length]
length(A)A.length
function make_matrix(m::Int, n::Int)
    A = zeros(m, n)
    for i in 1:m
        for j in 1:n
            A[i,j] = Float64(i + j)
        end
    end
    return A
end
# → [[2,3,4,...],[3,4,5,...],...]  (nested JS arrays)

Higher-Order Functions

JuliaJavaScript
map(f, arr)arr.map(f)
filter(f, arr)arr.filter(f)
any(f, arr), all(f, arr)arr.some(f), arr.every(f)
findfirst(f, arr)arr.findIndex(f)+1
reduce(f, arr)arr.reduce(f)

Strings

JuliaJavaScript
lowercase, uppercase.toLowerCase(), .toUpperCase()
contains, occursin.includes()
startswith, endswith.startsWith(), .endsWith()
split, join.split(), .join()
replace.replaceAll()
strip, lstrip, rstrip.trim(), .trimStart(), .trimEnd()
repeat, chop, chomp, reverse.repeat(), .slice(0,-1), etc.
string(...) concatenationTemplate literals
f(s::String) = contains(lowercase(s), "hello")
# → s.toLowerCase().includes("hello")

Broadcasting

Julia's dot-syntax broadcasts compile to chained .map() calls. Scalar-array, array-array, and nested broadcasting all work.

JuliaJavaScript
sin.(x)x.map(v => Math.sin(v))
x .* y (scalar-array)x.map(v => v * y)
x .* y (array-array)x.map((v,i) => v * y[i])
Nested: sin.(x .* f)Chained .map()
f(x::Vector{Float64}, freq::Float64) = sin.(x .* freq)
# → x.map(_b => _b * freq).map(_b => Math.sin(_b))

Control Flow

JuliaJavaScript
if/elseif/elseif/else if/else
for i in 1:n (single + nested)while(true) loops
while loopswhile loops
Short-circuit &&, ||Same
Ternary a ? b : cSame
try/catchtry/catch

Functions & Structs

JuliaJavaScript
Named functionsfunction name() {}
Closures (captured variables)JS closures
@noinline functionsPreserved as :invoke in IR
struct fields + constructorclass with constructor
Field access obj.fieldobj.field
setfield! (mutable)obj.field = val
struct Point; x::Float64; y::Float64; end
dist(p::Point) = sqrt(p.x^2 + p.y^2)
# → class Point { constructor(x, y) { this.x = x; this.y = y; } }
# → function dist(p) { return Math.sqrt(p.x*p.x + p.y*p.y); }

Collections

JuliaJavaScript
Dict{K,V}Map
Set{T}Set
Dict: setindex!, getindex, delete!, get, haskey.set(), .get(), .delete(), .has()
Set: push!, delete!, in.add(), .delete(), .has()

IO & Escape Hatch

JuliaJavaScript
println(...)console.log(...)
print(...)console.log(...)
parse(Int, s)parseInt(s, 10)
parse(Float64, s)parseFloat(s)
typeof, isatypeof, instanceof
convert(T, x)x (identity)
Float64(x), Int(x)+(x), (x)|0
isempty(x)x.length === 0
js("raw code")Raw JS emission
js("document.title = 'Hello'")
js("console.log('value:', \$1)", my_value)  # $1 substituted with compiled expression

Construction Helpers

JuliaJavaScript
zeros(n), ones(n), fill(v,n)new Array(n).fill(...)
zeros(m,n), ones(m,n), fill(v,m,n)jl_ndarray(val, [m,n]) → nested arrays

Package Registry

Register custom JavaScript output for any Julia package function. When JST encounters a call to a registered function, it invokes your compiler instead of trying to transpile the Julia implementation.

import JavaScriptTarget as JST

JST.register_package_compilation!(MyPkg, :my_func) do ctx, kwargs, pos_args
    items_js = pos_args[1]
    return "$(items_js).customMethod()"
end

Built-in Plotly support: JST.register_plotly_compilations!(MyModule)

Not Yet Transpiled

These operations are planned but not yet implemented. Contributions welcome.

CategoryJuliaStatus
Linear AlgebraA * B (matrix multiply)Use manual loops for now
transpose(A), A'Planned
det, inv, eigenPlanned (via package registry)
Array Opsreshape(A, m, n)Planned
hcat, vcatPlanned
view, @viewPlanned
enumerate (standalone)Works in for-loop context
StringsRegex matchingPlanned
Unicode operationsBasic support via runtime
Numbersrand(), randn()Planned (Math.random())
Complex{T}Planned
Rational{T}Not planned

Will Not Transpile

These Julia features cannot be transpiled to browser JavaScript due to fundamental platform constraints.

CategoryReason
File I/O (open, read, write)No filesystem in browser
Networking (HTTP, sockets)Browser security model
Multi-threading (Threads, @spawn)JS is single-threaded (use Web Workers separately)
Metaprogramming (@eval, eval, Meta.parse)No Julia runtime in browser
C interop (ccall, @ccall)No native binaries
Package loading (using, import at runtime)Static transpilation only

optimize=false

Use optimize=false for functions that build arrays dynamically. Optimized IR can eliminate array allocations that are needed at runtime.

function make_data(n::Int, freq::Float64)
    x = Float64[]
    for i in 1:n
        push!(x, Float64(i) * 0.1)
    end
    y = sin.(x .* freq)
    return (x, y)
end

result = JST.compile(make_data, (Int, Float64); optimize=false)

JST auto-detects when optimize=false is needed and falls back automatically when used via Therapy.jl.