Skip to main content

Context Creation

These functions manage the lifecycle of JavaScript contexts (JSContext). A context represents a JavaScript realm with its own global objects and system objects. Multiple contexts can exist within a single runtime and share objects, similar to how frames of the same origin share JavaScript objects in a web browser.

JS_NewContext

Creates a new JavaScript context with all standard intrinsic objects.
JSRuntime*
required
The runtime in which to create the context
Returns: A new JSContext pointer, or NULL on failure.

Description

This function creates a fully-featured JavaScript context with all standard intrinsic objects including:
  • Base objects (Object, Function, Array, etc.)
  • Date
  • Eval
  • RegExp
  • JSON
  • Proxy
  • Map and Set
  • TypedArrays
  • Promise
  • BigInt
For memory-constrained environments, use JS_NewContextRaw() combined with selective intrinsic functions to create a minimal context.

Example

JS_FreeContext

Frees a JavaScript context and releases all associated resources.
JSContext*
required
The context to free

Description

This function releases all resources associated with the context, including:
  • All JavaScript objects created in the context
  • The global object and its properties
  • All pending exceptions
  • Internal data structures
You must free all contexts before freeing the runtime. Failing to do so will result in memory leaks.

Important Notes

  • Always call JS_FreeContext() before JS_FreeRuntime()
  • All JSValue objects created in this context should be freed before calling this function
  • Do not use the context pointer after calling this function

Example

JS_DupContext

Creates a new context that shares the same runtime and global objects.
JSContext*
required
The context to duplicate
Returns: A new JSContext pointer that shares objects with the original context, or NULL on failure.

Description

This function creates a new context within the same runtime. The new context:
  • Shares the same global object as the original context
  • Can access and modify objects from the original context
  • Behaves like the same JavaScript realm
  • Must be freed separately with JS_FreeContext()
This is useful for scenarios where you need multiple references to the same realm, such as implementing worker threads or isolating execution while sharing state.

Example

  • JS_NewContextRaw() - Create a minimal context without intrinsic objects
  • JS_GetRuntime() - Get the runtime associated with a context
  • JS_GetContextOpaque() / JS_SetContextOpaque() - Attach custom data to a context
  • JS_GetGlobalObject() - Get the global object for a context