Load - WebAssembly

Load
====

The **`load`** instructions, are used to load a number from memory onto the stack.

For the integer numbers, you can also load a narrower number from memory and extend it into a wider type, e.g. load an unsigned 8-bit number and convert it into an i32 (**`i32.load8_u`**). These instructions are separate for signed and unsigned numbers.

Try it
------

Syntax
------

```wasm
;; the offset from where to load the number
i32.const 0

;; load the number at position 0
i32.load
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.load` | `0x28` |
| `i64.load` | `0x29` |
| `f32.load` | `0x2a` |
| `f64.load` | `0x2b` |
| `i32.load8_s` | `0x2c` |
| `i32.load8_u` | `0x2d` |
| `i32.load16_s` | `0x2e` |
| `i32.load16_u` | `0x2f` |
| `i64.load8_s` | `0x30` |
| `i64.load8_u` | `0x31` |
| `i64.load16_s` | `0x32` |
| `i64.load16_u` | `0x33` |
| `i64.load32_s` | `0x34` |
| `i64.load32_u` | `0x35` |


Grow - WebAssembly

Grow
====

The **`grow`** instruction, increases the size of the memory instance by a specified number of pages, each page is sized 64KiB.

The **`grow`** instruction returns previous size of memory, in pages, if the operation was successful, and returns **`-1`** if the operation failed.

Try it
------

Syntax
------

```wasm
;; load the number of memory pages to grow the memory by
i32.const 3

;; grow the memory by 3 pages
memory.grow

;; the top item on the stack will now either be the previous number of pages (success) or `-1` (failure)
```

| Instruction | Binary opcode |
| --- | --- |
| `memory.grow` | `0x40` |


Store - WebAssembly

Store
=====

The **`store`** instructions, are used to store a number in memory.

For the integer numbers, you can also store a wide typed number as a narrower number in memory, e.g. store a 32-bit number in an 8-bit slot (**`i32.store8`**). If the number doesn't fit in the narrower number type it will wrap.

Try it
------

Syntax
------

```wasm
;; the offset in memory where to store the number
i32.const 0

;; the number to store
i32.const 20

;; store 20 at position 0
i32.store
```

| Instruction | Binary opcode |
| --- | --- |
| `i32.store` | `0x36` |
| `i64.store` | `0x37` |
| `f32.store` | `0x38` |
| `f64.store` | `0x39` |
| `i32.store8` | `0x3a` |
| `i32.store16` | `0x3b` |
| `i64.store8` | `0x3c` |
| `i64.store16` | `0x3d` |
| `i64.store32` | `0x3e` |


Size - WebAssembly

Size
====

The **`size`** instruction, returns the amount of pages the memory instance currently has, each page is sized 64KiB.

Try it
------

Syntax
------

```wasm
;; get the amount of pages the memory has
memory.size
```

| Instruction | Binary opcode |
| --- | --- |
| `memory.size` | `0x3f` |


WebAssembly.Memory - WebAssembly

WebAssembly.Memory
==================

The **`WebAssembly.Memory`** object is a resizable `ArrayBuffer` or `SharedArrayBuffer` that holds the raw bytes of memory accessed by a `WebAssembly.Instance`.

Both WebAssembly and JavaScript can create `Memory` objects. If you want to access the memory created in JS from Wasm or vice versa, you can pass a reference to the memory from one side to the other.

Constructor
-----------

`WebAssembly.Memory()`

Creates a new `Memory` object.

Instance properties
-------------------

`Memory.prototype.buffer` Read only

Returns the buffer contained in the memory.

Instance methods
----------------

`Memory.prototype.grow()`

Increases the size of the memory instance by a specified number of WebAssembly pages (each one is 64KiB in size). Detaches the previous `buffer`.

Examples
--------

### Creating a new Memory object

There are two ways to get a `WebAssembly.Memory` object. The first way is to construct it from JavaScript. The following snippet creates a new WebAssembly Memory instance with an initial size of 10 pages (640KiB), and a maximum size of 100 pages (6.4MiB). Its `buffer` property will return an `ArrayBuffer`.

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
});
```

The following example (see memory.html on GitHub, and view it live also) fetches and instantiates the loaded memory.wasm bytecode using the `WebAssembly.instantiateStreaming()` function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values.

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
});

WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
  js: { mem: memory },
}).then((obj) => {
  const summands = new Uint32Array(memory.buffer);
  for (let i = 0; i < 10; i++) {
    summands[i] = i;
  }
  const sum = obj.instance.exports.accumulate(0, 10);
  console.log(sum);
});
```

Another way to get a `WebAssembly.Memory` object is to have it exported by a WebAssembly module. This memory can be accessed in the `exports` property of the WebAssembly instance (after the memory is exported within the WebAssembly module). The following example imports a memory exported from WebAssembly with the name `memory`, and then prints out the first element of the memory, interpreted as an `Uint32Array`.

```js
WebAssembly.instantiateStreaming(fetch("memory.wasm")).then((obj) => {
  const values = new Uint32Array(obj.instance.exports.memory.buffer);
  console.log(values[0]);
});
```

### Creating a shared memory

By default, WebAssembly memories are unshared. You can create a shared memory from JavaScript by passing `shared: true` in the constructor's initialization object:

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
  shared: true,
});
```

This memory's `buffer` property will return a `SharedArrayBuffer`.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # memories |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Global - WebAssembly

WebAssembly.Global
==================

A **`WebAssembly.Global`** object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more `WebAssembly.Module` instances. This allows dynamic linking of multiple modules.

Constructor
-----------

`WebAssembly.Global()`

Creates a new `Global` object.

Global instances
----------------

All `Global` instances inherit from the `Global()` constructor's prototype object — this can be modified to affect all `Global` instances.

### Instance properties

`Global.prototype.constructor`

Returns the function that created this object's instance. By default this is the `WebAssembly.Global()` constructor.

`Global.prototype[@@toStringTag]`

The initial value of the @@toStringTag property is the String value "WebAssembly.Global".

`Global.prototype.value`

The value contained inside the global variable — this can be used to directly set and get the global's value.

### Instance methods

`Global.prototype.valueOf()`

Old-style method that returns the value contained inside the global variable.

Examples
--------

### Creating a new Global instance

The following example shows a new global instance being created using the `WebAssembly.Global()` constructor. It is being defined as a mutable `i32` type, with a value of 0.

The value of the global is then changed, first to `42` using the `Global.value` property, and then to 43 using the `incGlobal()` function exported out of the `global.wasm` module (this adds 1 to whatever value is given to it and then returns the new value).

```js
const output = document.getElementById("output");

function assertEq(msg, got, expected) {
  const result =
    got === expected
      ? `SUCCESS! Got: ${got}<br>`
      : `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
  output.innerHTML += `Testing ${msg}: ${result}`;
}

assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");

const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);

WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
  ({ instance }) => {
    assertEq(
      "getting initial value from wasm",
      instance.exports.getGlobal(),
      0,
    );
    global.value = 42;
    assertEq(
      "getting JS-updated value from wasm",
      instance.exports.getGlobal(),
      42,
    );
    instance.exports.incGlobal();
    assertEq("getting wasm-updated value from JS", global.value, 43);
  },
);
```

**Note:** You can see the example running live on GitHub; see also the source code.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # globals |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API
* Import/Export mutable globals proposal


WebAssembly.compileStreaming() - WebAssembly

WebAssembly.compileStreaming()
==============================

 The **`WebAssembly.compileStreaming()`** static method compiles a `WebAssembly.Module` directly from a streamed underlying source.
 This function is useful if it is necessary to compile a module before it can be instantiated (otherwise, the `WebAssembly.instantiateStreaming()` function should be used).

**Note:** Webpages that have strict Content Security Policy (CSP) might block WebAssembly from compiling and executing modules.
 For more information on allowing WebAssembly compilation and execution, see the script-src CSP.

Syntax
------

```js
WebAssembly.compileStreaming(source)
```

### Parameters

`source`

A `Response` object or a promise that will fulfill with one, representing the underlying source of a Wasm module you want to stream and compile.

### Return value

A `Promise` that resolves to a `WebAssembly.Module` object representing the compiled module.

### Exceptions

* If `source` is not a `Response` or `Promise` resolving to a `Response`, the promise rejects with a `TypeError`.
* If compilation fails, the promise rejects with a `WebAssembly.CompileError`.
* If the `source` is a `Promise` that rejects, the promise rejects with the error.
* If the `source`'s `Result` has an error (e.g. bad MIME type), the promise rejects with an error.
Examples
--------

### Compile streaming

The following example (see our compile-streaming.html demo on GitHub, and view it live also) directly streams a Wasm module from an underlying source then compiles it to a `WebAssembly.Module` object. Because the `compileStreaming()` function accepts a promise for a `Response` object, you can directly pass it a `Promise` from calling `fetch()`, without waiting for the promise to fulfill.

```js
const importObject = { imports: { imported\_func: (arg) => console.log(arg) } };

WebAssembly.compileStreaming(fetch("simple.wasm"))
  .then((module) => WebAssembly.instantiate(module, importObject))
  .then((instance) => instance.exports.exported\_func());
```

 The resulting module instance is then instantiated using
 `WebAssembly.instantiate()`, and the exported function invoked.

Specifications
--------------

| Specification |
| --- |
| WebAssembly Web API # dom-webassembly-compilestreaming |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Tag - WebAssembly

WebAssembly.Tag
===============

The **`WebAssembly.Tag`** object defines a *type* of a WebAssembly exception that can be thrown to/from WebAssembly code.

 When creating a `WebAssembly.Exception`, the tag defines the data types and order of the values carried by the exception.
 The same unique tag instance must be used to access the values of the exception (for example, when using `Exception.prototype.getArg()`).

Constructing an instance of `Tag` creates a new unique tag.
 This tag can be passed to a WebAssembly module as a tag import, where it will become a typed tag defined in the *tag section* of the WebAssembly module.
 You can also export a tag defined in a module and use it to inspect exceptions thrown from the module.

**Note:** You can't access the values of an exception with a new tag that just happens to have the same parameters; it's a different tag!
 This ensures that WebAssembly modules can keep exception information internal if required.
 Code can still catch and rethrow exceptions that it does not understand.

Constructor
-----------

`WebAssembly.Tag()`

Creates a new `WebAssembly.Tag` object.

Instance methods
----------------

`Tag.prototype.type()`

Returns the object defining the data-types array for the tag (as set in its constructor).

Examples
--------

This code snippet creates a new `Tag` instance.

```js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
```

The snippet below shows how we might pass it to a module **example.wasm** during instantiation, using an "import object".

```js
const importObject = {
  extmod: {
    exttag: tagToImport,
  },
};

WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject).then(
  (obj) => {
    // …
  },
);
```

The WebAssembly module might then import the tag as shown below:

```wasm
(module
  (import "extmod" "exttag" (tag $tagname (param i32 f32))
)
```

If the tag was used to throw an exception that propagated to JavaScript, we could use the tag to inspect its values.

**Note:** There are many alternatives. We could also use the tag to create a `WebAssembly.Exception` and throw that from a function called by WebAssembly.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface: Exception Handling # tags |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.CompileError - WebAssembly

WebAssembly.CompileError
========================

The **`WebAssembly.CompileError`** object indicates an error during WebAssembly decoding or validation.

Constructor
-----------

`WebAssembly.CompileError()`

Creates a new `WebAssembly.CompileError` object.

Instance properties
-------------------

`WebAssembly.CompileError.prototype.message`

Error message. Inherited from `Error`.

`WebAssembly.CompileError.prototype.name`

Error name. Inherited from `Error`.

`WebAssembly.CompileError.prototype.cause`

Error cause. Inherited from `Error`.

`WebAssembly.CompileError.prototype.fileName`
Non-standard

Path to file that raised this error. Inherited from `Error`.

`WebAssembly.CompileError.prototype.lineNumber`
Non-standard

Line number in file that raised this error. Inherited from `Error`.

`WebAssembly.CompileError.prototype.columnNumber`
Non-standard

Column number in line that raised this error. Inherited from `Error`.

`WebAssembly.CompileError.prototype.stack`
Non-standard

Stack trace. Inherited from `Error`.

Instance methods
----------------

`WebAssembly.CompileError.prototype.toString()`

Returns a string representing the specified `Error` object. Inherited from `Error`.

Examples
--------

### Creating a new CompileError instance

The following snippet creates a new `CompileError` instance, and logs its details to the console:

```js
try {
  throw new WebAssembly.CompileError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof CompileError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "CompileError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-compileerror |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Module - WebAssembly

WebAssembly.Module
==================

A **`WebAssembly.Module`** object contains stateless WebAssembly code that has already been compiled by the browser — this can be efficiently shared with Workers, and instantiated multiple times.

Constructor
-----------

`WebAssembly.Module()`

Creates a new `Module` object.

Static methods
--------------

`WebAssembly.Module.customSections()`

Given a `Module` and string, returns a copy of the contents of all custom sections in the module with the given string name.

`WebAssembly.Module.exports()`

Given a `Module`, returns an array containing descriptions of all the declared exports.

`WebAssembly.Module.imports()`

Given a `Module`, returns an array containing descriptions of all the declared imports.

Examples
--------

### Sending a compiled module to a worker

The following example compiles the loaded `simple.wasm` byte code using the `WebAssembly.compileStreaming()` method and sends the resulting `Module` instance to a worker using `postMessage()`.

See the `index-compile.html` source code or view it live.

```js
const worker = new Worker("wasm\_worker.js");

WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
  worker.postMessage(mod),
);
```

The worker function `wasm_worker.js` defines an import object for the module to use. The function then sets up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the `WebAssembly.instantiate()` method and invoke an exported function from inside it.

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

onmessage = (e) => {
  console.log("module received from main thread");
  const mod = e.data;

  WebAssembly.instantiate(mod, importObject).then((instance) => {
    instance.exports.exported\_func();
  });
};
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # modules |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.LinkError - WebAssembly

WebAssembly.LinkError
=====================

The **`WebAssembly.LinkError`** object indicates an error during module instantiation (besides traps from the start function).

Constructor
-----------

`WebAssembly.LinkError()`

Creates a new `WebAssembly.LinkError` object.

Instance properties
-------------------

`WebAssembly.LinkError.prototype.message`

Error message. Inherited from `Error`.

`WebAssembly.LinkError.prototype.name`

Error name. Inherited from `Error`.

`WebAssembly.LinkError.prototype.cause`

Error cause. Inherited from `Error`.

`WebAssembly.LinkError.prototype.fileName`
Non-standard

Path to file that raised this error. Inherited from `Error`.

`WebAssembly.LinkError.prototype.lineNumber`
Non-standard

Line number in file that raised this error. Inherited from `Error`.

`WebAssembly.LinkError.prototype.columnNumber`
Non-standard

Column number in line that raised this error. Inherited from `Error`.

`WebAssembly.LinkError.prototype.stack`
Non-standard

Stack trace. Inherited from `Error`.

Instance methods
----------------

`WebAssembly.LinkError.prototype.toString()`

Returns a string representing the specified `Error` object. Inherited from `Error`.

Examples
--------

### Creating a new LinkError instance

The following snippet creates a new `LinkError` instance, and logs its details to the console:

```js
try {
  throw new WebAssembly.LinkError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof LinkError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "LinkError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-linkerror |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.instantiate() - WebAssembly

WebAssembly.instantiate()
=========================

 The **`WebAssembly.instantiate()`** function allows you to
 compile and instantiate WebAssembly code. This function has two overloads:

* The primary overload takes the WebAssembly binary code, in the form of a typed array or
 `ArrayBuffer`, and performs both compilation and instantiation in one
 step. The returned `Promise` resolves to both a compiled
 `WebAssembly.Module` and its first `WebAssembly.Instance`.
* The secondary overload takes an already-compiled `WebAssembly.Module`
 and returns a `Promise` that resolves to an `Instance` of that
 `Module`. This overload is useful if the `Module` has already
 been compiled.

**Warning:** This method is not the most efficient way of fetching and
 instantiating Wasm modules. If at all possible, you should use the newer
 `WebAssembly.instantiateStreaming()` method instead, which fetches,
 compiles, and instantiates a module all in one step, directly from the raw bytecode,
 so doesn't require conversion to an `ArrayBuffer`.

Syntax
------

### Primary overload — taking Wasm binary code

```js
WebAssembly.instantiate(bufferSource, importObject);
```

#### Parameters

`bufferSource`

 A typed array or
 `ArrayBuffer` containing the binary code of the Wasm module you want to
 compile, or a `WebAssembly.Module`.

`importObject` Optional

 An object containing the values to be imported into the newly-created
 `Instance`, such as functions or `WebAssembly.Memory` objects.
 There must be one matching property for each declared import of the compiled module or
 else a `WebAssembly.LinkError` is thrown.

#### Return value

 A `Promise` that resolves to a `ResultObject` which contains two
 fields:

* `module`: A `WebAssembly.Module` object representing the compiled WebAssembly module. This `Module` can be instantiated again, shared via `postMessage()`, or cached.
* `instance`: A `WebAssembly.Instance` object that contains all the Exported WebAssembly functions.

#### Exceptions

* If either of the parameters are not of the correct type or structure,
 the promise rejects with a `TypeError`.
* If the operation fails, the promise rejects with a
 `WebAssembly.CompileError`, `WebAssembly.LinkError`, or
 `WebAssembly.RuntimeError`, depending on the cause of the failure.
### Secondary overload — taking a module object instance

```js
WebAssembly.instantiate(module, importObject);
```

#### Parameters

`module`

The `WebAssembly.Module` object to be instantiated.

`importObject` Optional

 An object containing the values to be imported into the newly-created
 `Instance`, such as functions or `WebAssembly.Memory` objects.
 There must be one matching property for each declared import of `module` or
 else a `WebAssembly.LinkError` is thrown.

#### Return value

A `Promise` that resolves to an `WebAssembly.Instance` object.

#### Exceptions

* If either of the parameters are not of the correct type or structure, a
 `TypeError` is thrown.
* If the operation fails, the promise rejects with a
 `WebAssembly.CompileError`, `WebAssembly.LinkError`, or
 `WebAssembly.RuntimeError`, depending on the cause of the failure.
Examples
--------

**Note:** You'll probably want to use `WebAssembly.instantiateStreaming()` in most cases, as it is more efficient than `instantiate()`.

### First overload example

 After fetching some WebAssembly bytecode using fetch, we compile and instantiate the
 module using the `WebAssembly.instantiate()` function, importing a
 JavaScript function into the WebAssembly Module in the process. We then call an Exported WebAssembly function
 that is exported by the `Instance`.

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.instantiate(bytes, importObject))
  .then((result) => result.instance.exports.exported\_func());
```

**Note:** You can also find this example at index.html
 on GitHub (view it live also).

### Second overload example

 The following example (see our index-compile.html
 demo on GitHub, and view it live also)
 compiles the loaded simple.wasm byte code using the
 `WebAssembly.compileStreaming()` method and then sends it to a worker using
 `postMessage()`.

```js
const worker = new Worker("wasm\_worker.js");

WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
  worker.postMessage(mod),
);
```

 In the worker (see
 `wasm_worker.js`)
 we define an import object for the module to use, then set up an event handler to
 receive the module from the main thread. When the module is received, we create an
 instance from it using the `WebAssembly.instantiate()` method and invoke an
 exported function from inside it.

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

onmessage = (e) => {
  console.log("module received from main thread");
  const mod = e.data;

  WebAssembly.instantiate(mod, importObject).then((instance) => {
    instance.exports.exported\_func();
  });
};
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-webassembly-instantiate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Exception - WebAssembly

WebAssembly.Exception
=====================

The **`WebAssembly.Exception`** object represents a runtime exception thrown from WebAssembly to JavaScript, or thrown from JavaScript to a WebAssembly exception handler.

 The constructor accepts a `WebAssembly.Tag`, an array of values, and an `options` object as arguments.
 The tag uniquely defines the *type* of an exception, including the order of its arguments and their data types.
 The same tag that was used to create the `Exception` is required to access the arguments of a thrown exception.
 Methods are provided to test whether an exception matches a particular tag, and also to get a particular value by index (if the exception matches specified tag).

 JavaScript and other client code can only access WebAssembly exception values, and visa versa, when the associated tag is shared (you can't just use another tag that happens to define the same data types).
 Without the matching tag, exceptions can be caught and re-thrown, but they can't be inspected.

 In order to make exception-throwing faster, exceptions thrown from WebAssembly generally do not include a stack trace.
 WebAssembly code that needs to provide a stack trace must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the constructor.
 The constructor may then return an exception with a stack trace attached to the `stack` property.

**Note:** This feature is available in Web Workers

Constructor
-----------

`WebAssembly.Exception()`

Creates a new `WebAssembly.Exception` object.

Instance methods
----------------

`Exception.prototype.is()`

Tests whether the exception matches a particular tag.

`Exception.prototype.getArg()`

Returns the data fields of an exception that matches a specified tag.

Instance properties
-------------------

`Exception.prototype.stack`
Non-standard

Returns the stack trace for the exception, or `undefined`.

Examples
--------

This example shows how to define a tag and import it into a module, then use it to throw an exception that is caught in JavaScript.

Consider the following WebAssembly code, which is assumed to be compiled to a file **example.wasm**.

* The module imports a tag that is referred to as `$tagname` internally and that has a single `i32` parameter.
 The tag expects the tag to be passed using module `extmod` and tag `exttag`.
* The `$throwException` function throws an exception using the `throw` instruction, taking the `$tagname` and the parameter argument.
* The module exports the function `run()` that throws an exception with the value "42".

```wasm
(module
  ;; import tag that will be referred to here as $tagname
  (import "extmod" "exttag" (tag $tagname (param i32)))

  ;; $throwException function throws i32 param as a $tagname exception
  (func $throwException (param $errorValueArg i32)
    local.get $errorValueArg
    throw $tagname
  )

  ;; Exported function "run" that calls $throwException
  (func (export "run")
    i32.const 42
    call $throwException
  )
)
```

 The code below calls `WebAssembly.instantiateStreaming` to import the **example.wasm** file, passing in an "import object" (`importObject`) that includes a new `WebAssembly.Tag` named `tagToImport`.
 The import object defines an object with properties that match the `import` statement in the WebAssembly code.

Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.

```js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32"] });

// Note: import object properties match the WebAssembly import statement!
const importObject = {
  extmod: {
    exttag: tagToImport,
  },
};

WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
  .then((obj) => {
    console.log(obj.instance.exports.run());
  })
  .catch((e) => {
    console.error(e);
    // Check we have the right tag for the exception
    // If so, use getArg() to inspect it
    if (e.is(tagToImport)) {
      console.log(`getArg 0 : ${e.getArg(tagToImport, 0)}`);
    }
  });

/\* Log output
example.js:40 WebAssembly.Exception: wasm exception
example.js:41 getArg 0 : 42
\*/
```

 The exception is caught in JavaScript using the `catch` block.
 We can see it is of type `WebAssembly.Exception`, but if we didn't have the right tag we couldn't do much else.

However, because we have a tag, we use `Exception.prototype.is()` to check that it's the right one, and because it is correct, we call `Exception.prototype.getArg()` to read the value of "42".

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface: Exception Handling # runtime-exceptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Instance - WebAssembly

WebAssembly.Instance
====================

A **`WebAssembly.Instance`** object is a stateful, executable instance of a `WebAssembly.Module`. `Instance` objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code from JavaScript.

Constructor
-----------

`WebAssembly.Instance()`

Creates a new `Instance` object.

Instance properties
-------------------

`exports`

Returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. Read-only.

Examples
--------

### Synchronously instantiating a WebAssembly module

The `WebAssembly.Instance()` constructor function can be called to synchronously instantiate a given `WebAssembly.Module` object, for example:

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => {
    const mod = new WebAssembly.Module(bytes);
    const instance = new WebAssembly.Instance(mod, importObject);
    instance.exports.exported\_func();
  });
```

The preferred way to get an `Instance` is asynchronously, for example using the `WebAssembly.instantiateStreaming()` function like this:

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported\_func(),
);
```

This also demonstrates how the `exports` property is used to access exported functions.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # instances |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.compile() - WebAssembly

WebAssembly.compile()
=====================

 The **`WebAssembly.compile()`** static method compiles WebAssembly binary code into a `WebAssembly.Module` object.
 This function is useful if it is necessary to compile a module before it can be instantiated (otherwise, the `WebAssembly.instantiate()` function should be used).

**Note:** Webpages that have strict Content Security Policy (CSP) might block WebAssembly from compiling and executing modules.
 For more information on allowing WebAssembly compilation and execution, see the script-src CSP.

Syntax
------

```js
WebAssembly.compile(bufferSource)
```

### Parameters

`bufferSource`

 A typed array or `ArrayBuffer`
 containing the binary code of the Wasm module you want to compile.

### Return value

 A `Promise` that resolves to a `WebAssembly.Module` object
 representing the compiled module.

### Exceptions

* If `bufferSource` is not a typed array or `ArrayBuffer`,
 the promise rejects with a `TypeError`.
* If compilation fails, the promise rejects with a
 `WebAssembly.CompileError`.
Examples
--------

### Using compile

 The following example compiles the loaded simple.wasm byte code using the
 `compile()` function and then sends it to a worker using postMessage().

```js
const worker = new Worker("wasm\_worker.js");

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.compile(bytes))
  .then((mod) => worker.postMessage(mod));
```

**Note:** You'll probably want to use
 `WebAssembly.compileStreaming()` in most cases, as it is more efficient
 than `compile()`.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-webassembly-compile |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.RuntimeError - WebAssembly

WebAssembly.RuntimeError
========================

The **`WebAssembly.RuntimeError`** object is the error type that is thrown whenever WebAssembly specifies a trap.

Constructor
-----------

`WebAssembly.RuntimeError()`

Creates a new `WebAssembly.RuntimeError` object.

Instance properties
-------------------

`WebAssembly.RuntimeError.prototype.message`

Error message. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.name`

Error name. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.cause`

Error cause. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.fileName`
Non-standard

Path to file that raised this error. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.lineNumber`
Non-standard

Line number in file that raised this error. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.columnNumber`
Non-standard

Column number in line that raised this error. Inherited from `Error`.

`WebAssembly.RuntimeError.prototype.stack`
Non-standard

Stack trace. Inherited from `Error`.

Instance methods
----------------

`WebAssembly.RuntimeError.prototype.toString()`

Returns a string representing the specified `Error` object. Inherited from `Error`.

Examples
--------

### Creating a new RuntimeError instance

The following snippet creates a new `RuntimeError` instance, and logs its details to the console:

```js
try {
  throw new WebAssembly.RuntimeError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof WebAssembly.RuntimeError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "RuntimeError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-runtimeerror |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.validate() - WebAssembly

WebAssembly.validate()
======================

 The **`WebAssembly.validate()`** static method validates a given typed array of WebAssembly binary
 code, returning whether the bytes form a valid Wasm module (`true`) or not
 (`false`).

Syntax
------

```js
WebAssembly.validate(bufferSource)
```

### Parameters

`bufferSource`

 A typed array or ArrayBuffer
 containing WebAssembly binary code to be validated.

### Return value

 A boolean that specifies whether `bufferSource` is valid Wasm code
 (`true`) or not (`false`).

### Exceptions

 If `bufferSource` is not a typed array or ArrayBuffer,
 a `TypeError` is thrown.

Examples
--------

### Using validate

 The following example (see the validate.html source code,
 and see it live too)
 fetches a Wasm module and converts it into a typed array.
 The `validate()` method is then used to check whether the module is valid.

```js
fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => {
    const valid = WebAssembly.validate(bytes);
    console.log(
      `The given bytes are ${valid ? "" : "not "}a valid Wasm module`,
    );
  });
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-webassembly-validate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table - WebAssembly

WebAssembly.Table
=================

The **`WebAssembly.Table`** object is a JavaScript wrapper object — an array-like structure representing a WebAssembly table, which stores homogeneous references. A table created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.

**Note:** Tables can currently only store function references, or host references, but this will likely be expanded in the future.

Constructor
-----------

`WebAssembly.Table()`

Creates a new `Table` object.

Instance properties
-------------------

`Table.prototype.length` Read only

Returns the length of the table, i.e. the number of elements in the table.

Instance methods
----------------

`Table.prototype.get()`

Accessor function — gets the element stored at a given index.

`Table.prototype.grow()`

Increases the size of the `Table` instance by a specified number of elements.

`Table.prototype.set()`

Sets an element stored at a given index to a given value.

Examples
--------

### Creating a new WebAssembly Table instance

The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of 2 elements. We then print out the table length and contents of the two indexes (retrieved via `Table.prototype.get()` to show that the length is two and both elements are `null`.

```js
const tbl = new WebAssembly.Table({ initial: 2, element: "anyfunc" });
console.log(tbl.length); // "2"
console.log(tbl.get(0)); // "null"
console.log(tbl.get(1)); // "null"
```

We then create an import object that contains the table:

```js
const importObj = {
  js: { tbl },
};
```

Finally, we load and instantiate a Wasm module (table2.wasm) using the `WebAssembly.instantiateStreaming()` method. The table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation). So after instantiation, the table still has length 2, but the elements now contain callable Exported WebAssembly Functions which we can call from JS.

```js
WebAssembly.instantiateStreaming(fetch("table2.wasm"), importObject).then(
  (obj) => {
    console.log(tbl.length);
    console.log(tbl.get(0)());
    console.log(tbl.get(1)());
  },
);
```

Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. `get(0)()` rather than `get(0)`) .

This example shows that we're creating and accessing the table from JavaScript, but the same table is visible and callable inside the Wasm instance too.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # tables |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.instantiateStreaming() - WebAssembly

WebAssembly.instantiateStreaming()
==================================

 The **`WebAssembly.instantiateStreaming()`** static method compiles
 and instantiates a WebAssembly module directly from a streamed underlying source. This
 is the most efficient, optimized way to load Wasm code.

**Note:** Webpages that have strict Content Security Policy (CSP) might block WebAssembly from compiling and executing modules.
 For more information on allowing WebAssembly compilation and execution, see the script-src CSP.

Syntax
------

```js
WebAssembly.instantiateStreaming(source, importObject)
```

### Parameters

`source`

 A `Response`
 object or a promise that will fulfill with one, representing the underlying source of
 a Wasm module you want to stream, compile, and instantiate.

`importObject` Optional

 An object containing the values to be imported into the newly-created
 `Instance`, such as functions or `WebAssembly.Memory` objects.
 There must be one matching property for each declared import of the compiled module or
 else a
 `WebAssembly.LinkError`
 is thrown.

### Return value

 A `Promise` that resolves to a `ResultObject` which contains two
 fields:

* `module`: A `WebAssembly.Module` object representing the
 compiled WebAssembly module. This `Module` can be instantiated again or
 shared via postMessage().
* `instance`: A `WebAssembly.Instance` object that contains all
 the Exported WebAssembly functions.
### Exceptions

* If either of the parameters are not of the correct type or structure, a
 `TypeError` is thrown.
* If the operation fails, the promise rejects with a
 `WebAssembly.CompileError`, `WebAssembly.LinkError`, or
 `WebAssembly.RuntimeError`, depending on the cause of the failure.
Examples
--------

### Instantiating streaming

 The following example (see our instantiate-streaming.html
 demo on GitHub, and view it live also)
 directly streams a Wasm module from an underlying source then
 compiles and instantiates it, the promise fulfilling with a `ResultObject`.
 Because the `instantiateStreaming()` function accepts a promise for a `Response`
 object, you can directly pass it a `fetch()`
 call, and it will pass the response into the function when it fulfills.

```js
const importObject = { imports: { imported\_func: (arg) => console.log(arg) } };

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported\_func(),
);
```

 The `ResultObject`'s instance member is then accessed, and the contained
 exported function invoked.

**Note:** For this to work, `.wasm` files should be returned
 with an `application/wasm` MIME type by the server.

Specifications
--------------

| Specification |
| --- |
| WebAssembly Web API # dom-webassembly-instantiatestreaming |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Global() constructor - WebAssembly

WebAssembly.Global() constructor
================================

 A **`WebAssembly.Global()`** constructor creates a new `Global` object representing a global variable instance, accessible from both JavaScript and importable/exportable across one or more `WebAssembly.Module` instances.
 This allows dynamic linking of multiple modules.

Syntax
------

```js
new WebAssembly.Global(descriptor, value)
```

### Parameters

`descriptor`

An object, which contains two properties:

* `value`: A string representing the
 data type of the global. This can be any one of:
    + `i32`: A 32-bit integer.
    + `i64`: A 64-bit integer. (In JavaScript, this is represented as a `BigInt`)
    + `f32`: A 32-bit floating point number.
    + `f64`: A 64-bit floating point number.
    + `v128`: A 128-bit vector.
    + `externref`: A host reference.
    + `anyfunc`: A function reference.
* `mutable`: A boolean value that determines whether the global is
 mutable or not. By default, this is `false`.

`value`

 The value the variable contains. This can be any value, as long as its type matches the variable's data type.
 If no value is specified, a typed 0 value is used where the value of `descriptor.value` is one of `i32`, `i64`, `f32`, or `f64`, and `null` is used if `descriptor.value` is `externref` or `anyfunc` (as specified by the `DefaultValue` algorithm).

Examples
--------

### Creating a new Global instance

 The following example shows a new global instance being created using the `WebAssembly.Global()` constructor.
 It is being defined as a mutable `i32` type, with a value of 0.

The value of the global is then changed, first to `42` using the `Global.value` property, and then to 43 using the `incGlobal()` function exported out of the `global.wasm` module (this adds 1 to whatever value is given to it and then returns the new value).

```js
const output = document.getElementById("output");

function assertEq(msg, got, expected) {
  const result =
    got === expected
      ? `SUCCESS! Got: ${got}<br>`
      : `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
  output.innerHTML += `Testing ${msg}: ${result}`;
}

assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");

const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);

WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
  ({ instance }) => {
    assertEq(
      "getting initial value from wasm",
      instance.exports.getGlobal(),
      0,
    );
    global.value = 42;
    assertEq(
      "getting JS-updated value from wasm",
      instance.exports.getGlobal(),
      42,
    );
    instance.exports.incGlobal();
    assertEq("getting wasm-updated value from JS", global.value, 43);
  },
);
```

**Note:** You can see the example running live on GitHub;
 see also the source code.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-global-global |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API
* Import/Export mutable globals proposal


WebAssembly.RuntimeError() constructor - WebAssembly

WebAssembly.RuntimeError() constructor
======================================

 The **`WebAssembly.RuntimeError()`** constructor creates a new
 WebAssembly `RuntimeError` object — the type that is thrown whenever
 WebAssembly specifies a trap.

Syntax
------

```js
new WebAssembly.RuntimeError()
new WebAssembly.RuntimeError(message)
new WebAssembly.RuntimeError(message, options)
new WebAssembly.RuntimeError(message, fileName)
new WebAssembly.RuntimeError(message, fileName, lineNumber)
```

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception.

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception.

Examples
--------

### Creating a new RuntimeError instance

 The following snippet creates a new `RuntimeError` instance, and logs its
 details to the console:

```js
try {
  throw new WebAssembly.RuntimeError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof WebAssembly.RuntimeError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "RuntimeError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-runtimeerror |
| ECMAScript Language Specification # sec-nativeerror-constructors |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.CompileError() constructor - WebAssembly

WebAssembly.CompileError() constructor
======================================

 The **`WebAssembly.CompileError()`** constructor creates a new
 WebAssembly `CompileError` object, which indicates an error during
 WebAssembly decoding or validation.

Syntax
------

```js
new WebAssembly.CompileError()
new WebAssembly.CompileError(message)
new WebAssembly.CompileError(message, options)
new WebAssembly.CompileError(message, fileName)
new WebAssembly.CompileError(message, fileName, lineNumber)
```

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception.

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception.

Examples
--------

### Creating a new CompileError instance

 The following snippet creates a new `CompileError` instance, and logs its
 details to the console:

```js
try {
  throw new WebAssembly.CompileError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof CompileError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "CompileError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-compileerror |
| ECMAScript Language Specification # sec-nativeerror-constructors |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Tag() constructor - WebAssembly

WebAssembly.Tag() constructor
=============================

The **`WebAssembly.Tag()`** constructor creates a new `WebAssembly.Tag` object.

Syntax
------

```js
new WebAssembly.Tag(type)
```

### Parameters

`type`

An object that can contain the following members:

`parameters`

An array of data types (`"i32"`, `"i64"`, `"f32"`, `"f64"`, `"v128"`, `"externref"`, `"anyfunc"`).

### Exceptions

`TypeError`

Thrown if at least one of these conditions are met:

* The `type` parameter is not an object.
* The `type.parameters` property is not supplied.
* The `type.parameters` contains an unsupported data type.

Examples
--------

This creates a tag with two values.

```js
const tag = new WebAssembly.Tag({ parameters: ["i32", "i64"] });
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface: Exception Handling # dom-tag-tag |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Tag.prototype.type() - WebAssembly

WebAssembly.Tag.prototype.type()
================================

The **`type()`** prototype method of the `Tag` object can be used to get the sequence of data types associated with the tag.

Syntax
------

```js
type()
```

### Parameters

None

### Return value

An object with a property named `parameters` that references the array of data types associated with this `Tag`.

This is a copy of the `type` object that was originally passed into the `Tag()` constructor.

Examples
--------

 This code snippet creates a tag defining two data types and then exports them using `type()`.
 The result is printed to the console:

```js
const tag = new WebAssembly.Tag({ parameters: ["i32", "i64"] });
console.log(tag.type());

// Console output:
// Object { parameters: (2) […] }
// parameters: Array [ "i32", "i64" ]
// <prototype>: Object { … }
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface: Exception Handling # dom-tag-type |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Memory() constructor - WebAssembly

WebAssembly.Memory() constructor
================================

The **`WebAssembly.Memory()`** constructor creates a new `Memory` object whose `buffer` property is a resizable `ArrayBuffer` or `SharedArrayBuffer` that holds the raw bytes of memory accessed by a `WebAssembly.Instance`.

A memory object created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly, provided that the code constructed the object, or has been given the object.

Both WebAssembly and JavaScript can create `Memory` objects. If you want to access the memory created in JS from Wasm or vice versa, you can pass a reference to the memory from one side to the other.

Syntax
------

```js
new WebAssembly.Memory(memoryDescriptor)
```

### Parameters

`memoryDescriptor`

An object that can contain the following members:

`initial`

The initial size of the WebAssembly Memory, in units of WebAssembly pages.

`maximum` Optional

 The maximum size the WebAssembly Memory is allowed to grow to, in units of
 WebAssembly pages. When present, the `maximum` parameter acts as a hint
 to the engine to reserve memory up front. However, the engine may ignore or clamp
 this reservation request. Unshared WebAssembly memories don't need to set a
 `maximum`, but shared memories do.

`shared` Optional

 A boolean value that defines whether the memory is a shared memory or not. If
 set to `true`, it is a shared memory. The default is `false`.

**Note:** A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB.

### Exceptions

`TypeError`

Thrown if at least one of these conditions is met:

* `memoryDescriptor` is not an object.
* `initial` is not specified.
* `shared` is present and `true`, yet `maximum` is not specified.

`RangeError`

Thrown if at least one of these conditions is met:

* `maximum` is specified and is smaller than `initial`.
* `initial` exceeds 65,536 (2^16). 2^16 pages is 2^16 \* 64KiB = 4GiB bytes, which is the maximum range that a Wasm module can address, as Wasm currently only allows 32-bit addressing.
* Allocation fails. This may occur due to attempting to allocate too much at once, or if the User Agent is otherwise out of memory.

Examples
--------

### Creating a new Memory instance

There are two ways to get a `WebAssembly.Memory` object: construct it from JavaScript, or have it exported by a WebAssembly module.

The following example (see memory.html on GitHub, and view it live also) creates a new WebAssembly Memory instance with an initial size of 10 pages (640KiB), and a maximum size of 100 pages (6.4MiB). The example fetches and instantiates the loaded memory.wasm bytecode using the `WebAssembly.instantiateStreaming()` function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values. The `Memory` object's `buffer` property will return an `ArrayBuffer`.

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
});

WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
  js: { mem: memory },
}).then((obj) => {
  const summands = new Uint32Array(memory.buffer);
  for (let i = 0; i < 10; i++) {
    summands[i] = i;
  }
  const sum = obj.instance.exports.accumulate(0, 10);
  console.log(sum);
});
```

### Creating a shared memory

 By default, WebAssembly memories are unshared.
 You can create a shared memory
 from JavaScript by passing `shared: true` in the constructor's initialization object:

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
  shared: true,
});
```

This memory's `buffer` property will return a `SharedArrayBuffer`.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-memory-memory |

The `shared` attribute is only documented in the Threading proposal for WebAssembly and not part of the official specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Memory.prototype.buffer - WebAssembly

WebAssembly.Memory.prototype.buffer
===================================

The read-only **`buffer`** prototype property of the `WebAssembly.Memory` object returns the buffer contained in the memory. Depending on whether or not the memory was constructed with `shared: true`, the buffer is either an `ArrayBuffer` or a `SharedArrayBuffer`.

Examples
--------

### Using buffer

The following example (see memory.html on GitHub, and view it live also) fetches and instantiates the loaded memory.wasm bytecode using the `WebAssembly.instantiateStreaming()` function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values.

```js
const memory = new WebAssembly.Memory({
  initial: 10,
  maximum: 100,
});

WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
  js: { mem: memory },
}).then((obj) => {
  const summands = new Uint32Array(memory.buffer);
  for (let i = 0; i < 10; i++) {
    summands[i] = i;
  }
  const sum = obj.instance.exports.accumulate(0, 10);
  console.log(sum);
});
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-memory-buffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Memory.prototype.grow() - WebAssembly

WebAssembly.Memory.prototype.grow()
===================================

The **`grow()`** prototype method of the `WebAssembly.Memory` object increases the size of the memory instance by a specified number of WebAssembly pages.

Syntax
------

```js
grow(delta)
```

### Parameters

`delta`

The number of WebAssembly pages you want to grow the memory by (each one is 64KiB in size).

### Return value

The previous size of the memory, in units of WebAssembly pages.

### Exceptions

* `RangeError`: If the current size added with `delta` exceeds the Memory instance's maximum size capacity.
Examples
--------

### Using grow

The following example creates a new WebAssembly Memory instance with an initial size of 1 page (64KiB), and a maximum size of 10 pages (640KiB).

```js
const memory = new WebAssembly.Memory({
  initial: 1,
  maximum: 10,
});
```

We can then grow the instance by one page like so:

```js
const bytesPerPage = 64 \* 1024;
console.log(memory.buffer.byteLength / bytesPerPage); // "1"
console.log(memory.grow(1)); // "1"
console.log(memory.buffer.byteLength / bytesPerPage); // "2"
```

Note the return value of `grow()` here is the previous number of WebAssembly pages.

### Detachment upon growing

 Every call to `grow` will detach any references to the old `buffer`, even for `grow(0)`!
 Detachment means that the `ArrayBuffer`'s `byteLength` becomes zero, and it no longer has bytes accessible to JavaScript.
 Accessing the `buffer` property after calling `grow`, will yield an `ArrayBuffer` with the correct length.

```js
const memory = new WebAssembly.Memory({
  initial: 1,
});
const oldMemoryView = new Uint8Array(memory.buffer);
memory.grow(1);
// the array is empty!
console.log(oldMemoryView); // Uint8Array []
```

```js
const memory = new WebAssembly.Memory({
  initial: 1,
});
memory.grow(1);
const currentMemoryView = new Uint8Array(memory.buffer);
// the array is full of zeros
console.log(currentMemoryView); // Uint8Array(131072) [ 0, 0, 0, ... ]
// 131072 = 64KiB \* 2
```

For a shared `Memory` instance, the initial `buffer` (which would be a `SharedArrayBuffer` in such case) will not become detached, but rather its length will not be updated. Accesses to the `buffer` property after growing will yield a larger `SharedArrayBuffer` which may access a larger span of memory than the buffer from before growing the `Memory`. Every `SharedArrayBuffer` from the `buffer` property will all refer to the start of the same memory address range, and thus manipulate the same data.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-memory-grow |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Module.customSections() - WebAssembly

WebAssembly.Module.customSections()
===================================

 The **`WebAssembly.Module.customSections()`** static method returns a copy
 of the contents of all custom sections in the given module with the given string name.

Syntax
------

```js
WebAssembly.Module.customSections(module, sectionName)
```

### Parameters

`module`

 The `WebAssembly.Module` object whose custom sections are being
 considered.

`sectionName`

The string name of the desired custom section.

### Return value

A (possibly empty) array containing `ArrayBuffer` copies of the contents of all custom sections matching `sectionName`.

### Exceptions

 If `module` is not a `WebAssembly.Module` object instance, a
 `TypeError` is thrown.

Description
-----------

 A Wasm module consists of a sequence of **sections**. Most of these
 sections are fully specified and validated by the Wasm spec, but modules can also
 contain **custom sections** that are ignored and skipped over during
 validation. (Read High level structure
 for information on section structures, and how normal sections
 ("known sections") and custom sections are distinguished.)

 This provides developers with a way to include custom data inside Wasm modules for other purposes,
 for example the name custom section,
 which allows developers to provide names for all the functions and
 locals in the module (like "symbols" in a native build).

 Note that the WebAssembly text format currently doesn't have a syntax specified for
 adding new custom sections; you can however add a name section to your Wasm during
 conversion from text format over to Wasm. The `wast2wasm` command available as part of
 the wabt tool has a
 `--debug-names` option — specify this during conversion to get a Wasm with a
 names custom section, for example:

```bash
wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names
```

Examples
--------

### Using customSections

 The following example uses `WebAssembly.Module.customSections` to check
 if a loaded module instance contains a "name" custom section. A module contains a "name" custom section if `WebAssembly.Module.customSections`
 returns an `ArrayBuffer` with a length greater than 0.

 See custom-section.html source code
 and live example.

```js
WebAssembly.compileStreaming(fetch("simple-name-section.wasm")).then((mod) => {
  const nameSections = WebAssembly.Module.customSections(mod, "name");
  if (nameSections.length !== 0) {
    console.log("Module contains a name section");
    console.log(nameSections[0]);
  }
});
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-module-customsections |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Module.exports() - WebAssembly

WebAssembly.Module.exports()
============================

 The **`WebAssembly.Module.exports()`** static method returns an
 array containing descriptions of all the declared exports of the given
 `Module`.

Syntax
------

```js
WebAssembly.Module.exports(module)
```

### Parameters

`module`

A `WebAssembly.Module` object.

### Return value

An array containing objects representing the exported functions of the given module.

### Exceptions

 If module is not a `WebAssembly.Module` object instance, a
 `TypeError` is thrown.

Examples
--------

### Using exports

 The following example (see our index-compile.html
 demo on GitHub, and view it live also)
 compiles the loaded simple.wasm byte code using the
 `WebAssembly.compileStreaming()` method and then sends it to a worker using postMessage().

```js
const worker = new Worker("wasm\_worker.js");

WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
  worker.postMessage(mod),
);
```

 In the worker (see
 `wasm_worker.js`)
 we define an import object for the module to use, then set up an event handler to
 receive the module from the main thread. When the module is received, we create an
 instance from it using the `WebAssembly.Instantiate()` method, invoke an
 exported function from inside it, then show how we can return information on the
 available exports on a module using `WebAssembly.Module.exports`.

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

onmessage = (e) => {
  console.log("module received from main thread");
  const mod = e.data;

  WebAssembly.instantiate(mod, importObject).then((instance) => {
    instance.exports.exported\_func();
  });

  const exports = WebAssembly.Module.exports(mod);
  console.log(exports[0]);
};
```

The `exports[0]` output looks like this:

```js
{ name: "exported\_func", kind: "function" }
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-module-exports |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Module() constructor - WebAssembly

WebAssembly.Module() constructor
================================

 A **`WebAssembly.Module()`** constructor creates a new Module
 object containing stateless WebAssembly code that has already been compiled by the
 browser and can be efficiently shared with Workers, and instantiated multiple times.

 The `WebAssembly.Module()` constructor function can be called to
 synchronously compile given WebAssembly binary code. However, the primary way to get a
 `Module` is through an asynchronous compilation function like
 `WebAssembly.compile()`.

**Note:** Webpages that have strict Content Security Policy (CSP) might block WebAssembly from compiling and executing modules.
 For more information on allowing WebAssembly compilation and execution, see the script-src CSP.

Syntax
------

**Warning:** Since compilation for large modules can be expensive,
 developers should only use the `Module()` constructor when synchronous
 compilation is absolutely required; the asynchronous
 `WebAssembly.compileStreaming()` method should be used at all other times.

```js
new WebAssembly.Module(bufferSource)
```

### Parameters

`bufferSource`

 A typed array or ArrayBuffer
 containing the binary code of the Wasm module you want to compile.

#### Exceptions

* If the parameter is not of the correct type or structure, a
 `TypeError` is thrown.
* If compilation fails, the constructor rejects with a
 `WebAssembly.CompileError`.
* Some browsers may throw a `RangeError`, as they prohibit compilation and instantiation of Wasm with large buffers on the UI thread.
Examples
--------

### Synchronously compiling a WebAssembly module

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

function createWasmModule(bytes) {
  return new WebAssembly.Module(bytes);
}

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => {
    const mod = createWasmModule(bytes);
    WebAssembly.instantiate(mod, importObject).then((result) =>
      result.exports.exported\_func(),
    );
  });
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-module-module |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Module.imports() - WebAssembly

WebAssembly.Module.imports()
============================

 The **`WebAssembly.Module.imports()`** static method returns an array
 containing descriptions of all the declared imports of the given `Module`.

Syntax
------

```js
WebAssembly.Module.imports(module)
```

### Parameters

`module`

A `WebAssembly.Module` object.

### Return value

An array containing objects representing the imported functions of the given module.

### Exceptions

 If module is not a `WebAssembly.Module` object instance, a
 `TypeError` is thrown.

Examples
--------

### Using imports

The following example compiles a loaded Wasm module and queries the module's imports.

 See imports.html source code and
 live version.

```js
WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) => {
  const imports = WebAssembly.Module.imports(mod);
  console.log(imports[0]);
});
```

The console log displays the following description for the imported module:

```js
{ module: "imports", name: "imported\_func", kind: "function" }
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-module-imports |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Instance.prototype.exports - WebAssembly

WebAssembly.Instance.prototype.exports
======================================

 The **`exports`** readonly property of the
 `WebAssembly.Instance` object prototype returns an object containing as its
 members all the functions exported from the WebAssembly module instance, to allow them
 to be accessed and used by JavaScript.

Examples
--------

### Using exports

 After fetching some WebAssembly bytecode using fetch, we compile and instantiate the
 module using the `WebAssembly.instantiateStreaming()` function, importing a
 JavaScript function into the WebAssembly Module in the process. We then call an Exported WebAssembly function
 that is exported by the `Instance`.

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported\_func(),
);
```

**Note:** You can also find this example as instantiate-streaming.html
 on GitHub (view it live also).

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-instance-exports |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Instance() constructor - WebAssembly

WebAssembly.Instance() constructor
==================================

 The **`WebAssembly.Instance()`** constructor creates a new
 `Instance` object which is a stateful, executable instance of a
 `WebAssembly.Module`.

Syntax
------

**Warning:** Since instantiation for large modules can be expensive,
 developers should only use the `Instance()` constructor when synchronous
 instantiation is absolutely required; the asynchronous
 `WebAssembly.instantiateStreaming()` method should be used at all other
 times.

```js
new WebAssembly.Instance(module, importObject);
```

### Parameters

`module`

The `WebAssembly.Module` object to be instantiated.

`importObject` Optional

 An object containing the values to be imported into the newly-created
 `Instance`, such as functions or `WebAssembly.Memory` objects.
 There must be one matching property for each declared import of `module` or
 else a `WebAssembly.LinkError` is thrown.

#### Exceptions

* If either of the parameters are not of the correct type or structure, a
 `TypeError` is thrown.
* If the operation fails, one of
 `WebAssembly.CompileError`, `WebAssembly.LinkError`, or
 `WebAssembly.RuntimeError` are thrown, depending on the cause of the failure.
* Some browsers may throw a `RangeError`, as they prohibit compilation and instantiation of Wasm with large buffers on the UI thread.
Examples
--------

### Synchronously instantiating a WebAssembly module

 The `WebAssembly.Instance()` constructor function can be called to
 synchronously instantiate a given `WebAssembly.Module` object, for example:

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => {
    const mod = new WebAssembly.Module(bytes);
    const instance = new WebAssembly.Instance(mod, importObject);
    instance.exports.exported\_func();
  });
```

 However, the preferred way to get an `Instance` is through the asynchronous
 `WebAssembly.instantiateStreaming()` function, for example like this:

```js
const importObject = {
  imports: {
    imported\_func(arg) {
      console.log(arg);
    },
  },
};

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported\_func(),
);
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-instance-instance |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.LinkError() constructor - WebAssembly

WebAssembly.LinkError() constructor
===================================

 The **`WebAssembly.LinkError()`** constructor creates a new
 WebAssembly `LinkError` object, which indicates an error during module
 instantiation (besides traps
 from the start function).

Syntax
------

```js
new WebAssembly.LinkError()
new WebAssembly.LinkError(message)
new WebAssembly.LinkError(message, options)
new WebAssembly.LinkError(message, fileName)
new WebAssembly.LinkError(message, fileName, lineNumber)
```

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception.

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception.

Examples
--------

### Creating a new LinkError instance

 The following snippet creates a new `LinkError` instance, and logs its
 details to the console:

```js
try {
  throw new WebAssembly.LinkError("Hello", "someFile", 10);
} catch (e) {
  console.log(e instanceof LinkError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "LinkError"
  console.log(e.fileName); // "someFile"
  console.log(e.lineNumber); // 10
  console.log(e.columnNumber); // 0
  console.log(e.stack); // returns the location where the code was run
}
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # exceptiondef-linkerror |
| ECMAScript Language Specification # sec-nativeerror-constructors |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table.prototype.set() - WebAssembly

WebAssembly.Table.prototype.set()
=================================

The **`set()`** prototype method of the `WebAssembly.Table` object mutates a reference stored at a given index to a different value.

Syntax
------

```js
set(index, value)
```

### Parameters

`index`

The index of the function reference you want to mutate.

`value`

The value you want to mutate the reference to. This must be a value of the table's element type. Depending on the type, it may be an exported WebAssembly function, a JavaScript wrapper for an underlying Wasm function, or a host reference.

### Return value

None (`undefined`).

### Exceptions

* If `index` is greater than or equal to `Table.prototype.length`, a `RangeError` is thrown.
* If `value` is not of the element type of the table, a `TypeError` is thrown.
Examples
--------

### Using Table.set

The following example (see table2.html source code and live version) creates a new WebAssembly Table instance with an initial size of two references. We then print out the table length and contents of the two indexes (retrieved via `Table.prototype.get()`) to show that the length is two, and the indexes currently contain no function references (they currently return `null`).

```js
const tbl = new WebAssembly.Table({ initial: 2, element: "anyfunc" });
console.log(tbl.length);
console.log(tbl.get(0));
console.log(tbl.get(1));
```

We then create an import object that contains a reference to the table:

```js
const importObj = {
  js: { tbl },
};
```

Finally, we load and instantiate a Wasm module (table2.wasm) using `WebAssembly.instantiateStreaming()`, print the table length, and invoke the two referenced functions that are now stored in the table. The `table2.wasm` module adds two function references to the table, both of which print out a simple value (see text representation:

```js
WebAssembly.instantiateStreaming(fetch("table2.wasm"), importObject).then(
  (obj) => {
    console.log(tbl.length);
    console.log(tbl.get(0)());
    console.log(tbl.get(1)());
  },
);
```

Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. `get(0)()` rather than `get(0)`) .

This example shows that we're creating and accessing the table from JavaScript, but the same table is visible and callable inside the Wasm instance, too.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-table-set |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table() constructor - WebAssembly

WebAssembly.Table() constructor
===============================

The **`WebAssembly.Table()`** constructor creates a new `Table` object of the given size and element type, filled with the provided value.

Syntax
------

```js
new WebAssembly.Table(tableDescriptor)
new WebAssembly.Table(tableDescriptor, value)
```

### Parameters

`tableDescriptor`

An object that can contain the following members:

`element`

A string representing the type of value to be stored in the table. This can have a value of `"anyfunc"` (functions) or `"externref"` (host references).

`initial`

The initial number of elements of the WebAssembly Table.

`maximum` Optional

The maximum number of elements the WebAssembly Table is allowed to grow to.

`value` Optional

The element to fill the newly-allocated space with.

### Exceptions

* If `tableDescriptor` is not an object, a `TypeError` is thrown.
* If `maximum` is specified and is smaller than `initial`, a `RangeError` is thrown.
* If `element` is not one of the reference types, then a `TypeError` is thrown.
* If `value` is not a value of the type `element`, a `TypeError` is thrown.
Examples
--------

### Creating a new WebAssembly Table instance

The following example creates a `WebAssembly.Table` instance with an initial size of 2 elements. The `WebAssembly.Table` contents are populated using a WebAssembly module and are accessible from JavaScript. When viewing the live example, open your developer console to display console log messages from the code snippets below.

This example uses the following reference files:

1. `table2.html`: An HTML file containing JavaScript that creates a `WebAssembly.Table` (source code)
2. `table2.wasm`: A WebAssembly module imported by the JavaScript code in `table2.html` (source code)

In `table2.html`, we create a `WebAssembly.Table`:

```js
const tbl = new WebAssembly.Table({
  initial: 2,
  element: "anyfunc",
});
```

We can retrieve the index contents using `Table.prototype.get()`:

```js
console.log(tbl.length); // a table with 2 elements
console.log(tbl.get(0)); // content for index 0 is null
console.log(tbl.get(1)); // content for index 1 is null
```

Next, we create an import object that contains the `WebAssembly.Table`:

```js
const importObject = {
  js: { tbl },
};
```

Next, we load and instantiate a WebAssembly module. The `table2.wasm` module defines a table containing two functions. The first function returns 42, and the second returns 83:

```wasm
(module
    (import "js" "tbl" (table 2 anyfunc))
    (func $f42 (result i32) i32.const 42)
    (func $f83 (result i32) i32.const 83)
    (elem (i32.const 0) $f42 $f83)
)
```

We instantiate `table2.wasm` using the `WebAssembly.instantiateStreaming()` method:

```js
const instantiating = WebAssembly.instantiateStreaming(
  fetch("table2.wasm"),
  importObject,
);
```

After instantiating `table2.wasm`, `tbl` is updated with the following:

* table length is still 2
* content for index 0 is now a function which returns 42
* content for index 1 is now a function which returns 83

The items at indexes 0 and 1 of the table are now callable Exported WebAssembly Functions. To call them, note that we must add the function invocation operator `()` after the `get()` call:

```js
instantiating.then((obj) => {
  console.log(tbl.length); // 2
  console.log(tbl.get(0)()); // 42
  console.log(tbl.get(1)()); // 83
});
```

While we are creating and accessing the `WebAssembly.Table` from JavaScript, the same `Table` is also visible and callable inside the WebAssembly instance.

### Creating a new WebAssembly Table instance with a value

The following example creates a new WebAssembly Table instance with 4 elements, full of the same object:

```js
const myObject = { hello: "world" };

const table = new WebAssembly.Table(
  {
    element: "externref",
    initial: 4,
    maximum: 4,
  },
  myObject,
);

console.log(myObject === table.get(2)); // true
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-table-table |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table.prototype.length - WebAssembly

WebAssembly.Table.prototype.length
==================================

The read-only **`length`** prototype property of the `WebAssembly.Table` object returns the length of the table, i.e. the number of elements in the table.

Examples
--------

### Using length

 The following example creates a new WebAssembly Table instance with an initial size of
 2 and a maximum size of 10:

```js
const table = new WebAssembly.Table({
  element: "anyfunc",
  initial: 2,
  maximum: 10,
});
```

Grow the table by 1 using `WebAssembly.grow()`:

```js
console.log(table.length); // 2
table.grow(1);
console.log(table.length); // 3
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-table-length |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table.prototype.grow() - WebAssembly

WebAssembly.Table.prototype.grow()
==================================

The **`grow()`** prototype method of the `WebAssembly.Table` object increases the size of the `Table` instance by a specified number of elements, filled with the provided value.

Syntax
------

```js
grow(delta)
grow(delta, value)
```

### Parameters

`delta`

The number of elements you want to grow the table by.

`value` Optional

The element to fill the newly-allocated space with.

### Return value

The previous length of the table.

### Exceptions

`RangeError`

Thrown in one of the following cases:

* If the current size added with `delta` exceeds the Table instance's maximum size capacity.
* If the client doesn't have enough memory for the allocation.

`TypeError`

Thrown if `value` is not a value of the element type of the table.

Examples
--------

### Using grow

 The following example creates a new WebAssembly Table instance with an initial size of
 2 and a maximum size of 10:

```js
const table = new WebAssembly.Table({
  element: "anyfunc",
  initial: 2,
  maximum: 10,
});
```

Grow the table by 1 element using `Table.grow()`:

```js
console.log(table.length); // 2
table.grow(1);
console.log(table.length); // 3
```

### Using grow with a value

 The following example creates a new WebAssembly `Table` instance with an initial size of
 0 and a maximum size of 4, filling it with an object:

```js
const myObject = { hello: "world" };

const table = new WebAssembly.Table({
  element: "externref",
  initial: 0,
  maximum: 4,
});
```

Grow the table by 4 units and fill it with a value using `WebAssembly.grow()`:

```js
table.grow(4, myObject);
console.log(myObject === table.get(2)); // true
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-table-grow |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Table.prototype.get() - WebAssembly

WebAssembly.Table.prototype.get()
=================================

The **`get()`** prototype method of the `WebAssembly.Table()` object retrieves the element stored at a given index.

Syntax
------

```js
get(index)
```

### Parameters

`index`

The index of the element you want to retrieve.

### Return value

Depending the element type of the Table, can be a function reference — this is an exported WebAssembly function, a JavaScript wrapper for an underlying Wasm function, or it can be a host reference.

### Exceptions

If *index* is greater than or equal to `Table.prototype.length`, a `RangeError` is thrown.

Examples
--------

### Using get

The following example (see table.html on GitHub, and view it live also) compiles and instantiates the loaded table.wasm byte code using the `WebAssembly.instantiateStreaming()` method. It then retrieves the references stored in the exported table.

```js
WebAssembly.instantiateStreaming(fetch("table.wasm")).then((obj) => {
  const tbl = obj.instance.exports.tbl;
  console.log(tbl.get(0)()); // 13
  console.log(tbl.get(1)()); // 42
});
```

Note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. `get(0)()` rather than `get(0)`) — it is a function rather than a simple value.

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface # dom-table-get |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview page
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Exception.prototype.stack - WebAssembly

WebAssembly.Exception.prototype.stack
=====================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The read-only **`stack`** property of an object instance of type `WebAssembly.Exception` *may* contain a stack trace.

Exceptions from WebAssembly code do not include a stack trace by default.

 If WebAssembly code needs to provide a stack trace, it must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the constructor.
 The virtual machine can then attach a stack trace to the exception object returned by the constructor.

**Note:** Stack traces are not normally sent from WebAssembly code to improve performance.
 The ability to add stack traces to these exceptions is provided for developer tooling, and is not generally recommended for broader use.

Value
-----

A string containing the stack trace, or `undefined` if no trace has been assigned.

 The stack trace string lists the locations of each operation on the stack in WebAssembly format.
 This is a human-readable string indicating the URL, name of the function type called, the function index, and its offset in the module binary.
 It has approximately this format (see stack trace conventions in the specification for more information):
```

${url}:wasm-function[${funcIndex}]:${pcOffset}
```

Examples
--------

This example demonstrate how to throw an exception from WebAssembly that includes a stack trace.

 Consider the following WebAssembly code, which is assumed to be compiled to a file named **example.wasm**.
 This imports a tag, which it refers to as `$tagname` internally, and imports a function that it refers to as `$throwExnWithStack`.
 It exports the method `run` that can be called by external code to call `$throwExnWithStack` (and hence the JavaScript function).

```wasm
(module
  ;; import tag that will be referred to here as $tagname
  (import "extmod" "exttag" (tag $tagname (param i32)))

  ;; import function that will be referred to here as $throwExnWithStack
  (import "extmod" "throwExnWithStack" (func $throwExnWithStack (param i32)))

  ;; call $throwExnWithStack passing 42 as parameter
  (func (export "run")
    i32.const 42
    call $throwExnWithStack
  )
)
```

 The JavaScript code below defines a new tag `tag` and the function `throwExceptionWithStack`.
 These are passed to the WebAssembly module in the `importObject` when it is instantiated.

 Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
 The stack is then logged from the `catch` statement.

```js
const tag = new WebAssembly.Tag({ parameters: ["i32"] });

function throwExceptionWithStack(param) {
  // Note: We declare the exception with "{traceStack: true}"
  throw new WebAssembly.Exception(tag, [param], { traceStack: true });
}

// Note: importObject properties match the WebAssembly import statements.
const importObject = {
  extmod: {
    exttag: tag,
    throwExnWithStack: throwExceptionWithStack,
  },
};

WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
  .then((obj) => {
    console.log(obj.instance.exports.run());
  })
  .catch((e) => {
    console.log(`stack: ${e.stack}`);
  });

//Log output (something like):
// stack: throwExceptionWithStack@http://<url>/main.js:76:9
// @http://<url>/example.wasm:wasm-function[3]:0x73
// @http://<url>/main.js:82:38
```

The most "relevant" part of this code is the line where the exception is created:

```js
new WebAssembly.Exception(tag, [param], { traceStack: true });
```

 Passing in `{traceStack: true}` tells the WebAssembly virtual machine that it should attach a stack trace to the returned `WebAssembly.Exception`.
 Without this, the stack would be `undefined`.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API


WebAssembly.Exception.prototype.is() - WebAssembly

WebAssembly.Exception.prototype.is()
====================================

The **`is()`** prototype method of the `Exception` object can be used to test if the `Exception` matches a given tag.

 The method might be used to test that a tag is correct before passing it to `Exception.prototype.getArg()` to get the passed values.
 It can be used on tags created in JavaScript or created in WebAssembly code and exported to JavaScript.

**Note:** It is not enough that the tag has an identical sequence of data types — it must have the same *identity* (be the same tag) as was used to create the exception.

Syntax
------

```js
is(tag)
```

### Parameters

`tag`

An `WebAssembly.Tag` that can be checked to verify the type of the exception.

### Return value

A boolean `true` if the specified tag matches the exception, and `false` otherwise.

Examples
--------

The code below shows how to use `is()` to verify that a tag matches an `Exception`.

```js
// Create tag and use it to create an exception
const tag1 = new WebAssembly.Tag({ parameters: ["i32", "f64"] });
const exception1 = new WebAssembly.Exception(tag1, [42, 42.3]);

// Verify that "tag1" matches this exception
console.log(`Tag1: ${exception1.is(tag1)}`);

// Log output:
// Tag1: true
```

We can also demonstrate that this exception will not match another tag even if the tag is created with the same parameters.

```js
// Create a new tag (with same parameters) and verify it does not match the exception
const tag2 = new WebAssembly.Tag({ parameters: ["i32", "f64"] });
console.log(`Tag2: ${exception1.is(tag2)}`);

// Log output:
// Tag2: false
```

Specifications
--------------

| Specification |
| --- |
| WebAssembly JavaScript Interface: Exception Handling # dom-exception-is |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebAssembly overview
* WebAssembly concepts
* Using the WebAssembly JavaScript API