Warning: Reason support is experimental. We are looking for beta-tester and contributors.

The Js_of_ocaml library

This page provides an overview of the Js_of_ocaml type system for representing JavaScript values in OCaml. For practical examples, see the bindings guide.

Core concept: Js.t

All JavaScript values in OCaml are wrapped in the Js.t type. This phantom type ensures type safety when interacting with JavaScript.

'a Js.t    (* An OCaml type representing a JavaScript value *)

Type mappings

OCaml and JavaScript represent values differently. The table below shows the correspondence:

OCaml type Js_of_ocaml type JavaScript type
int int (direct) Number
float Js.number Js.t Number
bool bool Js.t Boolean
string Js.js_string Js.t String
array Js.js_array Js.t Array

Integers can be used directly. Other types require conversion functions like Js.string, Js.bool, etc. See Type conversions for details and examples.

JavaScript objects

JavaScript objects are represented using OCaml's object types:

< field1 : type1; field2 : type2; ... > Js.t

Each "method" in the OCaml type represents a JavaScript property or method. The property type determines access:

Type Meaning
t Js.readonly_prop Read-only property
t Js.writeonly_prop Write-only property
t Js.prop Read/write property
t1 -> ... -> tn -> t Js.meth Method

See Binding a JS object for examples.

Nullable and optional values

JavaScript has null and undefined. Js_of_ocaml provides:

  • Js.Opt - For values that may be null
  • Js.Optdef - For values that may be undefined

See Handling null and undefined for usage.

Functions

OCaml and JavaScript have different calling conventions (partial application vs. undefined for missing args). Use:

  • Js.wrap_callback - Wrap OCaml functions for JavaScript
  • Js.Unsafe.fun_call - Call JavaScript functions from OCaml

See Calling JS functions and Passing OCaml functions to JavaScript.

Syntax extension

The PPX syntax extension provides convenient syntax:

obj##.prop          (* Get property *)
obj##.prop := v     (* Set property *)
obj##meth arg       (* Call method *)
new%js constr args  (* Call constructor *)
object%js ... end   (* Create object literal *)

JSON serialization

The Js_of_ocaml.Json module provides marshaling between OCaml values and JSON strings:

(* OCaml value -> JSON string *)
let json : Js.js_string Js.t = Json.output value

(* JSON string -> OCaml value (unsafe, like Marshal) *)
let value : 'a = Json.unsafe_input json

For type-safe JSON handling, use ppx_deriving_json.

API reference