Packages

package js

Types, methods and values for interoperability with JavaScript libraries.

This package is only relevant to the Scala.js compiler, and should not be referenced by any project compiled to the JVM.

Guide

General documentation on Scala.js is available at http://www.scala-js.org/doc/.

Overview

The trait js.Any is the root of the hierarchy of JavaScript types. This package defines important subtypes of js.Any that are defined in the standard library of ECMAScript 5.1 (or ES 6, with a label in the documentation), such as js.Object, js.Array and js.RegExp.

Implicit conversions to and from standard Scala types to their equivalent in JavaScript are provided. For example, from Scala functions to JavaScript functions and back.

The most important subtypes of js.Any declared in this package are:

The trait js.Dynamic is a special subtrait of js.Any. It can represent any JavaScript value in a dynamically-typed way. It is possible to call any method and read and write any field of a value of type js.Dynamic.

There are no explicit definitions for JavaScript primitive types, as one could expect, because the corresponding Scala types stand in their stead:

  • Boolean is the type of primitive JavaScript booleans
  • Double is the type of primitive JavaScript numbers
  • String is the type of primitive JavaScript strings (or null)
  • Unit is the type of the JavaScript undefined value
  • Null is the type of the JavaScript null value

js.UndefOr gives a scala.Option-like interface where the JavaScript value undefined takes the role of None.

A | B is an unboxed pseudo-union type, suitable to type values that admit several unrelated types in facade types.

Linear Supertypes
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. js
  2. AnyRef
  3. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Type Members

  1. trait Any extends AnyRef

    Root of the hierarchy of JavaScript types.

    Root of the hierarchy of JavaScript types.

    Subtypes of js.Any are JavaScript types, which have different semantics and guarantees than Scala types (subtypes of AnyRef and AnyVal). Operations on JavaScript types behave as the corresponding operations in the JavaScript language.

    You can implement JavaScript types in Scala.js. The implementation (i.e., the method and constructor bodies) will follow Scala semantics, but the constructor and methods will be called using JavaScript semantics (e.g., runtime dispatch).

    A JavaScript type that is annotated with @js.native is a facade type to APIs implemented in JavaScript code. Its implementation is irrelevant and never emitted. As such, all members must be defined with their right-hand-side being js.native. Further, native JavaScript types must be annotated with one of @JSGlobal, @JSImport, @JSGlobalScope to specify where to fetch it from.

    In most cases, you should not directly extend this trait, but rather extend js.Object.

    It is not possible to define traits or classes that inherit both from this trait and a strict subtype of AnyRef. In fact, you should think of js.Any as a third direct subclass of scala.Any, besides scala.AnyRef and scala.AnyVal.

    See the JavaScript interoperability guide of Scala.js for more details.

    Annotations
    @JSType()
  2. class Array[A] extends Object with Iterable[A]

    Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.

    Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's size length grow or shrink at any time, JavaScript arrays are not guaranteed to be dense. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

    MDN

    To construct a new array with uninitialized elements, use the constructor of this class. To construct a new array with specified elements, as if you used the array literal syntax in JavaScript, use the Array.apply method instead.

    A

    Type of the elements of the array

    Annotations
    @JSType() @native() @JSGlobal()
  3. final class ArrayOps[A] extends ArrayLike[A, Array[A]] with Builder[A, Array[A]]

    Equivalent of scm.ArrayOps for js.Array.

    Equivalent of scm.ArrayOps for js.Array.

    Annotations
    @inline()
  4. final class BigInt extends Object

    ECMAScript 2020

    ECMAScript 2020

    A built-in object that provides a way to represent whole numbers larger than 2 ^ 53 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.

    BigInt can be used for arbitrarily large integers.

    Annotations
    @JSType() @native() @JSGlobal()
    See also

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

  5. final class ConstructorTag[T <: Any] extends AnyVal

    Stores the JS constructor function of a JS class.

    Stores the JS constructor function of a JS class.

    A ConstructorTag[T] holds the constructor function of a JS class, as retrieved by js.constructorOf[T]. Similarly to ClassTags, ConstructorTags can be implicitly materialized when T is statically known to be a JS class, i.e., a valid type argument to js.constructorOf.

  6. class Date extends Object

    Creates a JavaScript Date instance that represents a single moment in time.

    Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
    Note

    js.Date objects can represent an *invalid date*, for example, if they are constructed from a String that cannot be parsed as a date. Most methods of such a js.Date will return NaN (for those returning a Double) or other invalid values.

  7. sealed trait Dictionary[A] extends Any

    Dictionary "view" of a JavaScript value.

    Dictionary "view" of a JavaScript value.

    Using objects as dictionaries (maps from strings to values) through their properties is a common idiom in JavaScript. This trait lets you treat an object as such a dictionary, with the familiar API of a Map.

    To use it, cast your object, say x, into a Dictionary using

    val xDict = x.asInstanceOf[js.Dictionary[Int]]

    then use it as

    xDict("prop") = 5
    println(xDict.get("prop")) // displays Some(5)
    xDict -= "prop"            // removes the property "prop"
    println(xDict.get("prop")) // displays None

    To enumerate all the keys of a dictionary, use collection methods or for comprehensions. For example:

    for ((prop, value) <- xDict) {
      println(prop + " -> " + value)
    }

    Note that this does not enumerate properties in the prototype chain of xDict.

    This trait extends js.Any directly, because it is not safe to call methods of js.Object on it, given that the name of these methods could be used as keys in the dictionary.

    Annotations
    @JSType()
  8. sealed trait Dynamic extends Any with scala.Dynamic

    Dynamically typed JavaScript value.

    Dynamically typed JavaScript value.

    Values of this trait accept all possible JavaScript operations in a dynamically typed way. You can read and write any field, call any method, apply any JavaScript operator to values of this type.

    Annotations
    @JSType() @native()
  9. class Error extends Object
    Annotations
    @JSType() @native() @JSGlobal()
  10. class EvalError extends Error

    An instance representing an error that occurs regarding the global function eval().

    An instance representing an error that occurs regarding the global function eval().

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  11. class FinalizationRegistry[-A, -B, -C] extends Object

    ECMAScript 2021

    ECMAScript 2021

    A FinalizationRegistry object lets you request a callback when an object is garbage-collected.

    FinalizationRegistry provides a way to request that a cleanup callback get called at some point when an object registered with the registry has been reclaimed (garbage-collected). (Cleanup callbacks are sometimes called finalizers.)

    MDN

    A

    Type of the target object to register

    B

    Type of value to pass to the finalizer

    C

    Type of an unregistration token

    Annotations
    @JSType() @native() @JSGlobal()
  12. class Function extends Object

    The Function constructor creates a new Function object.

    The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

    Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function and calling it within your code, because functions declared with the function statement are parsed with the rest of the code.

    All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

    Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

    Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  13. trait Function0[+R] extends Function
    Annotations
    @JSType()
  14. trait Function1[-T1, +R] extends Function
    Annotations
    @JSType()
  15. trait Function2[-T1, -T2, +R] extends Function
    Annotations
    @JSType()
  16. trait Iterable[+A] extends Object

    ECMAScript 6 JavaScript Iterable.

    ECMAScript 6 JavaScript Iterable.

    Annotations
    @JSType()
  17. final class IterableOps[+A] extends collection.Iterable[A]

    Adapts a JavaScript Iterable to a Scala Iterable

    Adapts a JavaScript Iterable to a Scala Iterable

    Annotations
    @inline()
  18. trait Iterator[+A] extends Object

    ECMAScript 6 JavaScript Iterator.

    ECMAScript 6 JavaScript Iterator.

    Annotations
    @JSType()
  19. sealed abstract class JSConvertersLowPrioImplicits extends AnyRef
  20. trait JSNumberOps extends Any

    Operations on JavaScript numbers.

    Operations on JavaScript numbers.

    Annotations
    @JSType()
  21. trait JSStringOps extends Any

    Operations on JavaScript strings.

    Operations on JavaScript strings.

    The methods with an equivalent signature in String but with a different meaning are prefixed by js in this trait.

    Annotations
    @JSType()
  22. final case class JavaScriptException(exception: scala.Any) extends RuntimeException with Product with Serializable
  23. sealed trait LowPrioAnyImplicits extends LowestPrioAnyImplicits
  24. sealed trait LowestPrioAnyImplicits extends AnyRef
  25. class Map[K, V] extends Object with Iterable[Tuple2[K, V]]

    ECMAScript 2015

    ECMAScript 2015

    The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

    K

    A type of key.

    V

    A type of value.

    Annotations
    @JSType() @native() @JSGlobal()
    See also

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

  26. class Object extends Any

    Base class of all JavaScript objects.

    Base class of all JavaScript objects.

    Annotations
    @JSType() @native() @JSGlobal()
  27. class Promise[+A] extends Object with Thenable[A]

    ECMAScript 6 Promise of an asynchronous result.

    ECMAScript 6 Promise of an asynchronous result.

    Attention! The nature of this class, from the ECMAScript specification, makes it inherently un-typeable, because it is not type parametric.

    The signatures of the constructor and the methods then and catch are only valid provided that the values of A and B are not Thenables.

    We recommend to use Scala's Futures instead of Promise as much as possible. A Promise can be converted to a Future with .toFuture and back with .toJSPromise (provided by JSConverters).

    With

    import scala.scalajs.js.Thenable.Implicits._

    you can implicitly convert a Promise to a Future, and therefore you can directly use the methods of Future on Promises.

    Annotations
    @JSType() @native() @JSGlobal()
  28. trait PropertyDescriptor extends Object
    Annotations
    @JSType()
  29. class RangeError extends Error

    An instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

    An instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

    A RangeError is thrown when trying to pass a number as an argument to a function that does not allow a range that includes that number. This can be encountered when to create an array of an illegal length with the Array constructor, or when passing bad values to the numeric methods toExponential, toFixed, or toPrecision.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  30. class ReferenceError extends Error

    Represents an error when a non-existent variable is referenced.

    Represents an error when a non-existent variable is referenced.

    A ReferenceError is thrown when trying to dereference a variable that has not been declared.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  31. class RegExp extends Object

    The RegExp constructor creates a regular expression object for matching text with a pattern.

    The RegExp constructor creates a regular expression object for matching text with a pattern.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  32. class Set[T] extends Object with Iterable[T]

    ECMAScript 2015

    ECMAScript 2015

    The Set object lets you store unique values of any type, whether primitive values or object references.

    T

    A type of element.

    Annotations
    @JSType() @native() @JSGlobal()
    See also

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

  33. sealed trait Symbol extends Any

    ECMAScript 6 JavaScript Symbol.

    ECMAScript 6 JavaScript Symbol.

    Annotations
    @JSType() @native()
  34. class SyntaxError extends Error

    Represents an error when trying to interpret syntactically invalid code.

    Represents an error when trying to interpret syntactically invalid code.

    A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  35. trait Thenable[+A] extends Object

    A thing on which one can call the then method.

    A thing on which one can call the then method.

    Thenables are automatically transitively flattened by the then method of Thenables. In particular, this is true for Promises.

    Attention! The nature of this interface, from the ECMAScript specification, makes it inherently un-typeable, because it is not type parametric.

    The signature of the then method is only valid provided that the values of B do not have a then method.

    Annotations
    @JSType()
  36. trait ThisFunction extends Function

    A JavaScript function where this is considered as a first parameter.

    A JavaScript function where this is considered as a first parameter.

    Annotations
    @JSType()
    See also

    Calling JavaScript from Scala.js

  37. trait ThisFunction0[-T0, +R] extends Function with ThisFunction
    Annotations
    @JSType()
  38. trait ThisFunction1[-T0, -T1, +R] extends Function with ThisFunction
    Annotations
    @JSType()
  39. trait ThisFunction2[-T0, -T1, -T2, +R] extends Function with ThisFunction
    Annotations
    @JSType()
  40. sealed trait Tuple2[+T1, +T2] extends Object

    A tuple "view" of 2 elements of a JavaScript js.Array.

    A tuple "view" of 2 elements of a JavaScript js.Array.

    Supports implicit conversions to and from scala.Tuple2.

    To use it, cast your array into a js.Tuple2 using

    val array = js.Array[Any](42, "foobar")
    val tuple2 = array.asInstanceOf[js.Tuple2[Int, String]]

    or convert a Scala tuple

    val obj: js.Tuple2[Int, String] = (42, "foobar")
    Annotations
    @JSType()
  41. sealed trait Tuple3[+T1, +T2, +T3] extends Object

    A tuple "view" of 3 elements of a JavaScript js.Array.

    A tuple "view" of 3 elements of a JavaScript js.Array.

    Annotations
    @JSType()
    See also

    js.Tuple2

  42. class TypeError extends Error

    Represents an error when a value is not of the expected type.

    Represents an error when a value is not of the expected type.

    A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  43. class URIError extends Error

    Represents an error when a malformed URI is encountered.

    Represents an error when a malformed URI is encountered.

    A URIError is thrown when the URI handling functions are passed a malformed URI.

    MDN

    Annotations
    @JSType() @native() @JSGlobal()
  44. type UndefOr[+A] = |[A, Unit]

    Value of type A or the JS undefined value.

    Value of type A or the JS undefined value.

    This type is actually strictly equivalent to A | Unit, since Unit is the type of the undefined value.

    js.UndefOr[A] is the type of a value that can be either undefined or an A. It provides an API similar to that of scala.Option through the UndefOrOps implicit class, where undefined take the role of None.

    By extension, this type is also suited to typing optional fields in native JS types, i.e., fields that may not exist on the object.

  45. final class UndefOrOps[A] extends AnyVal

  46. sealed trait UnicodeNormalizationForm extends Any

    A Unicode Normalization Form.

    A Unicode Normalization Form.

    Annotations
    @JSType()
    See also

    js.JSStringOps.normalize

    Unicode Normalization Forms

  47. class WeakRef[+T] extends Object

    ECMAScript 2021

    ECMAScript 2021

    A WeakRef object lets you hold a weak reference to another object, without preventing that object from getting garbage-collected.

    MDN

    T

    unconstrained, but the constructor will throw a TypeError if targetObject is not an Object.

    Annotations
    @JSType() @native() @JSGlobal()
  48. final class WrappedArray[A] extends AbstractBuffer[A] with GenericTraversableTemplate[A, WrappedArray] with collection.mutable.IndexedSeq[A] with BufferLike[A, WrappedArray[A]] with ArrayLike[A, WrappedArray[A]] with Builder[A, WrappedArray[A]]

    Equivalent of scm.WrappedArray for js.Array.

    Equivalent of scm.WrappedArray for js.Array.

    Annotations
    @inline()
  49. final class WrappedDictionary[A] extends AbstractMap[String, A] with collection.mutable.Map[String, A] with MapLike[String, A, WrappedDictionary[A]]

    Wrapper to use a js.Dictionary as a scala.mutable.Map

    Wrapper to use a js.Dictionary as a scala.mutable.Map

    Annotations
    @inline()
  50. final class WrappedMap[K, V] extends AbstractMap[K, V] with collection.mutable.Map[K, V] with MapLike[K, V, WrappedMap[K, V]]

    Wrapper to use a js.Map as a scala.mutable.Map

    Wrapper to use a js.Map as a scala.mutable.Map

    Annotations
    @inline()
  51. final class WrappedSet[T] extends AbstractSet[T] with collection.mutable.Set[T] with SetLike[T, WrappedSet[T]]

    Wrapper to use a js.Set as a scala.mutable.Set

    Wrapper to use a js.Set as a scala.mutable.Set

    Annotations
    @inline()
  52. class native extends Annotation with StaticAnnotation

    Marks the annotated class, trait or object as a native JS entity.

    Marks the annotated class, trait or object as a native JS entity.

    Native JS entities are not implemented in Scala.js. They are facade types for native JS libraries.

    Only types extending js.Any can be annotated with @js.native. The body of all concrete members in a native JS class, trait or object must be = js.native.

    Annotations
    @field() @getter() @setter()
  53. sealed trait |[A, B] extends AnyRef

    Value of type A or B (union type).

    Value of type A or B (union type).

    Scala does not have union types, but they are important to many interoperability scenarios. This type provides a (partial) encoding of union types using implicit evidences.

    Annotations
    @JSType()

Value Members

  1. def constructorOf[T <: Any]: Dynamic

    Returns the constructor function of a JavaScript class.

    Returns the constructor function of a JavaScript class.

    The specified type parameter T must be a class type (i.e., valid for classOf[T]) and represent a class extending js.Any (not a trait nor an object).

  2. def constructorTag[T <: Any](implicit tag: ConstructorTag[T]): ConstructorTag[T]

    Makes explicit an implicitly available js.ConstructorTag.

  3. def dynamicImport[A](body: ⇒ A): Promise[A]

    ECMAScript 6 Dynamic import boundary for progressive module loading.

    ECMAScript 6 Dynamic import boundary for progressive module loading.

    val promise = js.dynamicImport {
      calculationNeedingLotsOfCode()
    }
    
    promise.foreach(println(_))

    In the example above, the code required for calculationNeedingLotsOfCode() is only loaded if the statement is actually executed.

  4. def eval(x: String): scala.Any

    Evaluates JavaScript code and returns the result.

    Evaluates JavaScript code and returns the result.

    Annotations
    @inline()
  5. def isUndefined(v: scala.Any): Boolean

    Tests whether the given value is undefined.

    Tests whether the given value is undefined.

    Annotations
    @inline()
  6. def native: Nothing

    Denotes a method body as native JavaScript.

    Denotes a method body as native JavaScript. For use in facade types:

    class MyJSClass extends js.Object {
      def myMethod(x: String): Int = js.native
    }
  7. def typeOf(x: scala.Any): String

    Returns the type of x as identified by typeof x in JavaScript.

  8. def undefined: UndefOr[Nothing]

    The undefined value.

    The undefined value.

    Annotations
    @inline()
  9. object Any extends LowPrioAnyImplicits

    Provides implicit conversions from Scala values to JavaScript values.

  10. object Array

    Factory for js.Array objects.

  11. object BigInt extends Object

    ECMAScript 2020

    ECMAScript 2020

    A companion object of BigInt class.

    Annotations
    @native() @JSGlobal()
    See also

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

  12. object ConstructorTag
  13. object Date extends Object

    Factory for js.Date objects.

    Factory for js.Date objects.

    Annotations
    @native() @JSGlobal()
  14. object Dictionary

    Factory for js.Dictionary instances.

  15. object Dynamic

    Factory for dynamically typed JavaScript values.

  16. object DynamicImplicits

    Provides implicit conversions and operations to write in JavaScript style with js.Dynamic.

    Provides implicit conversions and operations to write in JavaScript style with js.Dynamic.

    Be **very** careful when importing members of this object. You may want to selectively import the implicits that you want to reduce the likelihood of making mistakes.

  17. object Error extends Object
    Annotations
    @native() @JSGlobal()
  18. object EvalError extends Object
    Annotations
    @native() @JSGlobal()
  19. object Function extends Object
    Annotations
    @native() @JSGlobal()
  20. object Iterator
  21. object JSConverters extends JSConvertersLowPrioImplicits

    A collection of decorators that allow converting Scala types to corresponding JS facade types

  22. object JSNumberOps
  23. object JSON extends Object

    The JSON object contains methods for converting values to JavaScript Object Notation (JSON) and for converting JSON to values.

    The JSON object contains methods for converting values to JavaScript Object Notation (JSON) and for converting JSON to values.

    MDN

    Annotations
    @native() @JSGlobal()
  24. object JSStringOps
  25. object Map

    Factory for js.Map instances.

  26. object Math extends Object

    Math is a built-in object that has properties and methods for mathematical constants and functions.

    Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

    MDN

    Annotations
    @native() @JSGlobal()
  27. object Object extends Object

    The top-level Object JavaScript object.

    The top-level Object JavaScript object.

    Annotations
    @native() @JSGlobal()
  28. object Promise extends Object
    Annotations
    @native() @JSGlobal()
  29. object RangeError extends Object
    Annotations
    @native() @JSGlobal()
  30. object ReferenceError extends Object
    Annotations
    @native() @JSGlobal()
  31. object RegExp extends Object
    Annotations
    @native() @JSGlobal()
  32. object Set

    Factory for js.Set instances.

  33. object Symbol extends Object

    ECMAScript 6 Factory for js.Symbols and well-known symbols.

    ECMAScript 6 Factory for js.Symbols and well-known symbols.

    Annotations
    @native() @JSGlobal()
  34. object SyntaxError extends Object
    Annotations
    @native() @JSGlobal()
  35. object Thenable
  36. object ThisFunction
  37. object Tuple2
  38. object Tuple3
  39. object TypeError extends Object
    Annotations
    @native() @JSGlobal()
  40. object URIError extends Object
    Annotations
    @native() @JSGlobal()
  41. object URIUtils extends Object

    Methods related to URIs, provided by ECMAScript 5.1.

    Methods related to URIs, provided by ECMAScript 5.1.

    Annotations
    @native() @JSGlobalScope()
  42. object UndefOrOps
  43. object UnicodeNormalizationForm
  44. object WrappedArray extends SeqFactory[WrappedArray]

    Factory for js.WrappedArray.

    Factory for js.WrappedArray. Mainly provides the relevant CanBuildFromss and implicit conversions.

  45. object WrappedDictionary
  46. object WrappedMap
  47. object WrappedSet
  48. object defined
  49. object import

    ECMAScript 2020 Dynamic import(specifier) and meta-property import.meta.

  50. object new

    ECMAScript 2015 Meta-property new.target.

  51. object |

Inherited from AnyRef

Inherited from scala.Any

Ungrouped