- Qt 6.9
- Qt Qml
- Integrating QML and JavaScript
- JavaScript Host Environment
- Qt 6.9.3 Reference Documentation

Importing JavaScript Resources ◦ Memory Management in the JavaScript Engine

# JavaScript Host Environment

QML provides a JavaScript host environment tailored to writing QML applications. This environment is different from the host environment provided by a browser or a server-side JavaScript environment such as Node.js. For example, QML does not provide a `window` object or `DOM API` as commonly found in a browser environment.

## Common Base

Like a browser or server-side JavaScript environment, the QML runtime implements the ECMAScript Language Specification standard. This provides access to all of the built-in types and functions defined by the standard, such as Object, Array, and Math. The QML runtime implements the 7th edition of the standard.

Nullish Coalescing (`??`) (since Qt 5.15) and Optional Chaining (`?.`) (since Qt 6.2) are also implemented in the QML runtime.

Moreover, numeric literal separators (the underscores in `1_000_000`) are supported since Qt 6.8.

The standard ECMAScript built-ins are not explicitly documented in the QML documentation. For more information on their use, please refer to the ECMA-262 7th edition standard or one of the many online JavaScript reference and tutorial sites, such as the W3Schools JavaScript Reference (JavaScript Objects Reference section). Many sites focus on JavaScript in the browser, so in some cases you may need to double check the specification to determine whether a given function or object is part of standard ECMAScript or specific to the browser environment. In the case of the W3Schools link above, the `JavaScript Objects Reference` section generally covers the standard, while the `Browser Objects Reference` and `HTML DOM Objects Reference` sections are browser specific (and thus not applicable to QML).

## Type annotations and assertions

Function declarations in QML documents can, and should, contain type annotations. Type annotations are appended to the declaration of arguments and to the function itself, for annotating the return type. The following function takes an `int` and a `string` parameter, and returns a `QtObject`:

     function doThings(a: int, b: string) : QtObject { ... }

Type annotations help tools like Qt Creator and qmllint to make sense of the code and provide better diagnostics. Moreover, they make functions easier to use from C++. See Interacting with QML Objects from C++ for more information.

The exception to this rule are functions assigned to signal handlers: There, type annotations are forbidden to avoid a potential mismatch with the types of the signal. This does not cause issues for tooling, as the signal already provides the necessary information.

Note: In QML, enumerations are not types and can therefore not be used as type annotations. Their underlying numeric type, int or double, should be used instead.

Type assertions (sometimes called as-casts) can also be used in order to cast an object to a different object type. If the object is actually of the given type, then the type assertion returns the same object. If not, it returns `null`. In the following snippet we assert that the `parent` object is a `Rectangle` before accessing a specific member of it.

     Item {
         property color parentColor: (parent as Rectangle)?.color || "red"
     }

The optional chaining (`?.`) avoids throwing an exception if the parent is actually not a rectangle. In that case "red" is chosen as `parentColor`.

Since Qt 6.7 type annotations are always enforced when calling functions. Values are coerced to the required types as necessary. Previously, type annotations were ignored by the interpreter and the JIT compiler, but enforced by qmlcachegen and qmlsc when compiling to C++. This could lead to differences in behavior in some corner cases. In order to explicitly request the old behavior of the interpreter and JIT you can add the following to your QML document:

     pragma FunctionSignatureBehavior: Ignored

## QML Global Object

The QML JavaScript host environment implements a number of host objects and functions, as detailed in the QML Global Object documentation.

These host objects and functions are always available, regardless of whether any modules have been imported.

## JavaScript Objects and Functions

A list of the JavaScript objects, functions and properties supported by the QML engine can be found in the List of JavaScript Objects and Functions.

Note that QML makes the following modifications to native objects:

- An arg() function is added to the `String` prototype.
- Locale-aware conversion functions are added to the Date and Number prototypes.

In addition, QML also extends the behavior of the instanceof function to allow for type checking against QML types. This means that you may use it to verify that a variable is indeed the type you expect, for example:

     var v = something();
     if (!v instanceof Item) {
         throw new TypeError("I need an Item type!");
     }

     ...

## JavaScript Environment Restrictions

QML implements the following restrictions for JavaScript code:

- JavaScript code written in a `.qml` file cannot modify the global object. JavaScript code in a .js file can modify the global object, and those modifications will be visible to the .qml file when imported.

  In QML, the global object is constant - existing properties cannot be modified or deleted, and no new properties may be created.

  Most JavaScript programs do not intentionally modify the global object. However, JavaScript's automatic creation of undeclared variables is an implicit modification of the global object, and is prohibited in QML.

  Assuming that the `a` variable does not exist in the scope chain, the following code is illegal in QML:

       // Illegal modification of undeclared variable
       a = 1;
       for (var ii = 1; ii < 10; ++ii)
           a = a * ii;
       console.log("Result: " + a);

  It can be trivially modified to this legal code.

       var a = 1;
       for (var ii = 1; ii < 10; ++ii)
           a = a * ii;
       console.log("Result: " + a);

  Any attempt to modify the global object - either implicitly or explicitly - will cause an exception. If uncaught, this will result in a warning being printed, that includes the file and line number of the offending code.

- Global code is run in a reduced scope.

  During startup, if a QML file includes an external JavaScript file with "global" code, it is executed in a scope that contains only the external file itself and the global object. That is, it will not have access to the QML objects and properties it normally would.

  Global code that only accesses script local variables is permitted. This is an example of valid global code.

       var colors = [ "red", "blue", "green", "orange", "purple" ];

  Global code that accesses QML objects will not run correctly.

       // Invalid global code - the "rootObject" variable is undefined
       var initialPosition = { rootObject.x, rootObject.y }

  This restriction exists as the QML environment is not yet fully established. To run code after the environment setup has completed, see JavaScript in Application Startup Code.

- The value of `this` is undefined in QML in the majority of contexts.

  The `this` keyword is supported when binding properties from JavaScript. In QML binding expressions, QML signal handlers, and QML declared functions, `this` refers to the scope object. In all other situations, the value of `this` is undefined in QML.

  To refer to a specific object, provide an `id`. For example:

       Item {
           width: 200; height: 100
           function mouseAreaClicked(area) {
               console.log("Clicked in area at: " + area.x + ", " + area.y);
           }
           // This will pass area to the function
           MouseArea {
               id: area
               y: 50; height: 50; width: 200
               onClicked: mouseAreaClicked(area)
           }
       }

See also Scope and Naming Resolution.