Skip to main content

Primitive Types

In JavaScript, the primitive types are types of values that aren't objects. This page gives some simple examples of how to construct instances of various JavaScript primitive types, and you can follow the links to more detailed information in the API documentation.

Numbers#

The Context::number() method constructs a JavaScript number from any Rust number compatible with the f64 type. This includes both integers and floating-point numbers, so you can conveniently construct a JavaScript number from a literal number:

let i: Handle<JsNumber> = cx.number(42);let f: Handle<JsNumber> = cx.number(3.14);

For types that aren't implicitly convertible to f64, you can explicitly cast a number with Rust's as operator:

let size: usize = std::mem::size_of::<u128>();let n = cx.number(size as f64)

Keep in mind that for some types, explicit casts to f64 might be lossy, so you'll want to check whether the conversion you're doing is appropriate. Another option is to use the TryFrom API, which can help avoid loss of precision.

Strings#

The Context::string() method constructs a JavaScript string from a reference to a Rust string.

let s: Handle<JsString> = cx.string("foobar");

Booleans#

The Context::boolean() method constructs a JavaScript Boolean value.

let b: Handle<JsBoolean> = cx.boolean(true);

Undefined#

The Context::undefined() method constructs a JavaScript undefined value.

let u: Handle<JsUndefined> = cx.undefined();

Null#

The Context::null() method constructs a JavaScript null value.

let n: Handle<JsNull> = cx.null();