Table of contents
jsval is the type of JavaScript values in the JSAPI.
A C/C++ variable of type jsval can hold exactly the same values as a JavaScript var or property: string, number, object, boolean, null, or undefined. (Arrays, functions, and Errors are all objects.)
jsval is a variant type whose exact representation varies by architecture. Embeddings should not rely on observed representation details, the size of jsval, or whether jsval is a primitive type.
The are two major caveats about working with jsvals.
jsval is not particularly type-safe
The data in a jsval can be accessed using these JSAPI macros and functions:
| JS type | jsval type tests | jsval constants and constructors | jsval accessors |
|---|---|---|---|
null | JSVAL_IS_NULL(v) | JSVAL_NULL | |
undefined | JSVAL_IS_VOID(v) | JSVAL_VOID | |
| boolean | JSVAL_IS_BOOLEAN(v) | JSVAL_TRUE, JSVAL_FALSE, BOOLEAN_TO_JSVAL(b) | JSVAL_TO_BOOLEAN(v) |
| number | JSVAL_IS_NUMBER(v), JSVAL_IS_INT(v), JSVAL_IS_DOUBLE(v) | JSVAL_ZERO, JSVAL_ONE, INT_TO_JSVAL(i), DOUBLE_TO_JSVAL(d) | JSVAL_TO_INT(v), JSVAL_TO_DOUBLE(v) |
| string | JSVAL_IS_STRING(v) | STRING_TO_JSVAL(str) | JSVAL_TO_STRING(v), JS_GetStringChars(str), JS_GetStringLength(str) |
| object | JSVAL_IS_OBJECT(v) && !JSVAL_IS_NULL(v) | OBJECT_TO_JSVAL(obj) | JSVAL_TO_OBJECT(v) |
Note that JSVAL_IS_OBJECT() considers JSVAL_NULL to be an object.
jsvals are subject to garbage collection
A jsval can refer to a string, object, or number that's located in SpiderMonkey's garbage-collected heap.
The garbage collector is designed to automatically free unreachable memory. It is rather eager about its job. It's like a robot that goes around picking up everything that isn't nailed down and putting it in the trash. If an application has a jsval variable that refers to a JSObject, the garbage collector might not know you're using the JSObject. So it might free it, leaving a dangling pointer. The solution is to tell SpiderMonkey that you're using the object, then tell it again when you're done.
In short, your jsvals must be rooted or your program will randomly crash. In some places, SpiderMonkey provides already-rooted jsvals which you can use for variables. See SpiderMonkey Garbage Collection Tips.


Mozilla Developer Network