null: Wasm reference instruction

Baseline
Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2021.

The ref.null reference instruction creates a null reference of a given heap type.

Try it

(module
  (import "console" "log" (func $log (param externref)))
  (func $main
    ref.null extern
    call $log ;; log a null externref
  )
  (start $main)
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url), { console });

WAT syntax

ref.null heap_type
ref.null

The ref.null instruction.

Immediates

heap_type

The heap type of the null reference to create. This can be an abstract heap type such as func, extern or any, or the name or index of a type defined in the module, for example $my_struct_type.

Operand stack

[] -> [output:(ref null heap_type)]
output

A null reference of type (ref null heap_type). For example, ref.null func produces a null funcref, and ref.null extern produces a null externref.

Binary encoding

Instruction Binary format Example text => binary
ref.null 0xd0 ht:heap_type ref.null extern => 0xd0 0x6f

Description

The ref.null instruction creates a reference that points to nothing. Null references are commonly used to initialize nullable reference-typed locals, globals, and table elements before a real reference is available, or to represent "no value" when calling functions that take a nullable reference.

Because ref.null is a constant instruction, it can be used in constant expressions, such as the initializer of a global or an item in an elem segment.

When a null reference is passed to JavaScript, it is converted to null.

To check whether a reference is null, use ref.is_null.

Specifications

Specification
WebAssembly Core Specification
# -hrefsyntax-instr-refmathsfrefnullmathitht

Browser compatibility

See also