repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/rangeerror/index.md
--- title: RangeError slug: Web/JavaScript/Reference/Global_Objects/RangeError page-type: javascript-class browser-compat: javascript.builtins.RangeError --- {{JSRef}} The **`RangeError`** object indicates an error when a value is not in the set or range of allowed values. ## Description A `RangeError` is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value. This can be encountered when: - passing a value that is not one of the allowed string values to {{jsxref("String.prototype.normalize()")}}, or - when attempting to create an array of an illegal length with the {{jsxref("Array")}} constructor, or - when passing bad values to the numeric methods {{jsxref("Number.prototype.toExponential()")}}, {{jsxref("Number.prototype.toFixed()")}} or {{jsxref("Number.prototype.toPrecision()")}}. `RangeError` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}. `RangeError` is a subclass of {{jsxref("Error")}}. ## Constructor - {{jsxref("RangeError/RangeError", "RangeError()")}} - : Creates a new `RangeError` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Error")}}_. These properties are defined on `RangeError.prototype` and shared by all `RangeError` instances. - {{jsxref("Object/constructor", "RangeError.prototype.constructor")}} - : The constructor function that created the instance object. For `RangeError` instances, the initial value is the {{jsxref("RangeError/RangeError", "RangeError")}} constructor. - {{jsxref("Error/name", "RangeError.prototype.name")}} - : Represents the name for the type of error. For `RangeError.prototype.name`, the initial value is `"RangeError"`. ## Instance methods _Inherits instance methods from its parent {{jsxref("Error")}}_. ## Examples ### Using RangeError (for numeric values) ```js function check(n) { if (!(n >= -500 && n <= 500)) { throw new RangeError("The argument must be between -500 and 500."); } } try { check(2000); } catch (error) { if (error instanceof RangeError) { // Handle the error } } ``` ### Using RangeError (for non-numeric values) ```js function check(value) { if (!["apple", "banana", "carrot"].includes(value)) { throw new RangeError( 'The argument must be an "apple", "banana", or "carrot".', ); } } try { check("cabbage"); } catch (error) { if (error instanceof RangeError) { // Handle the error } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}} - {{jsxref("Array")}} - {{jsxref("Number.prototype.toExponential()")}} - {{jsxref("Number.prototype.toFixed()")}} - {{jsxref("Number.prototype.toPrecision()")}} - {{jsxref("String.prototype.normalize()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/rangeerror
data/mdn-content/files/en-us/web/javascript/reference/global_objects/rangeerror/rangeerror/index.md
--- title: RangeError() constructor slug: Web/JavaScript/Reference/Global_Objects/RangeError/RangeError page-type: javascript-constructor browser-compat: javascript.builtins.RangeError.RangeError --- {{JSRef}} The **`RangeError()`** constructor creates {{jsxref("RangeError")}} objects. ## Syntax ```js-nolint new RangeError() new RangeError(message) new RangeError(message, options) new RangeError(message, fileName) new RangeError(message, fileName, lineNumber) RangeError() RangeError(message) RangeError(message, options) RangeError(message, fileName) RangeError(message, fileName, lineNumber) ``` > **Note:** `RangeError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `RangeError` instance. ### Parameters - `message` {{optional_inline}} - : Human-readable description of the error. - `options` {{optional_inline}} - : An object that has the following properties: - `cause` {{optional_inline}} - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. - `fileName` {{optional_inline}} {{non-standard_inline}} - : The name of the file containing the code that caused the exception - `lineNumber` {{optional_inline}} {{non-standard_inline}} - : The line number of the code that caused the exception ## Examples ### Using RangeError (for numeric values) ```js function check(n) { if (!(n >= -500 && n <= 500)) { throw new RangeError("The argument must be between -500 and 500."); } } try { check(2000); } catch (error) { if (error instanceof RangeError) { // Handle the error } } ``` ### Using RangeError (for non-numeric values) ```js function check(value) { if (!["apple", "banana", "carrot"].includes(value)) { throw new RangeError( 'The argument must be an "apple", "banana", or "carrot".', ); } } try { check("cabbage"); } catch (error) { if (error instanceof RangeError) { // Handle the error } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}} - {{jsxref("Array")}} - {{jsxref("Number.prototype.toExponential()")}} - {{jsxref("Number.prototype.toFixed()")}} - {{jsxref("Number.prototype.toPrecision()")}} - {{jsxref("String.prototype.normalize()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/index.md
--- title: Symbol slug: Web/JavaScript/Reference/Global_Objects/Symbol page-type: javascript-class browser-compat: javascript.builtins.Symbol --- {{JSRef}} **`Symbol`** is a built-in object whose constructor returns a `symbol` [primitive](/en-US/docs/Glossary/Primitive) — also called a **Symbol value** or just a **Symbol** — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak {{Glossary("encapsulation")}}, or a weak form of [information hiding](https://en.wikipedia.org/wiki/Information_hiding). Every `Symbol()` call is guaranteed to return a unique Symbol. Every `Symbol.for("key")` call will always return the same Symbol for a given value of `"key"`. When `Symbol.for("key")` is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned. ## Description To create a new primitive Symbol, you write `Symbol()` with an optional string as its description: ```js const sym1 = Symbol(); const sym2 = Symbol("foo"); const sym3 = Symbol("foo"); ``` The above code creates three new Symbols. Note that `Symbol("foo")` does not coerce the string `"foo"` into a Symbol. It creates a new Symbol each time: ```js Symbol("foo") === Symbol("foo"); // false ``` The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}: ```js example-bad const sym = new Symbol(); // TypeError ``` This prevents authors from creating an explicit `Symbol` wrapper object instead of a new Symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, `new Boolean`, `new String` and `new Number`). If you really want to create a `Symbol` wrapper object, you can use the `Object()` function: ```js const sym = Symbol("foo"); typeof sym; // "symbol" const symObj = Object(sym); typeof symObj; // "object" ``` Because symbols are the only primitive data type that has reference identity (that is, you cannot create the same symbol twice), they behave like objects in some way. For example, they are garbage collectable and can therefore be stored in {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, {{jsxref("WeakRef")}}, and {{jsxref("FinalizationRegistry")}} objects. ### Shared Symbols in the global Symbol registry The above syntax using the `Symbol()` function will create a Symbol whose value remains unique throughout the lifetime of the program. To create Symbols available across files and even across realms (each of which has its own global scope), use the methods {{jsxref("Symbol.for()")}} and {{jsxref("Symbol.keyFor()")}} to set and retrieve Symbols from the global Symbol registry. Note that the "global Symbol registry" is only a fictitious concept and may not correspond to any internal data structure in the JavaScript engine — and even if such a registry exists, its content is not available to the JavaScript code, except through the `for()` and `keyFor()` methods. The method `Symbol.for(tokenString)` takes a string key and returns a symbol value from the registry, while `Symbol.keyFor(symbolValue)` takes a symbol value and returns the string key corresponding to it. Each is the other's inverse, so the following is `true`: ```js Symbol.keyFor(Symbol.for("tokenString")) === "tokenString"; // true ``` Because registered symbols can be arbitrarily created anywhere, they behave almost exactly like the strings they wrap. Therefore, they are not guaranteed to be unique and are not garbage collectable. Therefore, registered symbols are disallowed in {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, {{jsxref("WeakRef")}}, and {{jsxref("FinalizationRegistry")}} objects. ### Well-known Symbols All static properties of the `Symbol` constructor are Symbols themselves, whose values are constant across realms. They are known as _well-known Symbols_, and their purpose is to serve as "protocols" for certain built-in JavaScript operations, allowing users to customize the language's behavior. For example, if a constructor function has a method with {{jsxref("Symbol.hasInstance")}} as its name, this method will encode its behavior with the {{jsxref("Operators/instanceof", "instanceof")}} operator. Prior to well-known Symbols, JavaScript used normal properties to implement certain built-in operations. For example, the [`JSON.stringify`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) function will attempt to call each object's `toJSON()` method, and the [`String`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String) function will call the object's `toString()` and `valueOf()` methods. However, as more operations are added to the language, designating each operation a "magic property" can break backward compatibility and make the language's behavior harder to reason with. Well-known Symbols allow the customizations to be "invisible" from normal code, which typically only read string properties. In MDN and other sources, well-known symbol values are stylized by prefixing `@@`. For example, {{jsxref("Symbol.hasInstance")}} is written as `@@hasInstance`. This is because symbols don't have actual literal formats, but using `Symbol.hasInstance` does not reflect the ability of using other aliases to refer to the same symbol. This is like the difference between `Function.name` and `"Function"`. Well-known symbols do not have the concept of garbage collectability, because they come in a fixed set and are unique throughout the lifetime of the program, similar to intrinsic objects such as `Array.prototype`, so they are also allowed in {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, {{jsxref("WeakRef")}}, and {{jsxref("FinalizationRegistry")}} objects. ### Finding Symbol properties on objects The method {{jsxref("Object.getOwnPropertySymbols()")}} returns an array of Symbols and lets you find Symbol properties on a given object. Note that every object is initialized with no own Symbol properties, so that this array will be empty unless you've set Symbol properties on the object. ## Constructor - {{jsxref("Symbol/Symbol", "Symbol()")}} - : Creates a new `Symbol` object. It is not a constructor in the traditional sense, because it can only be called as a function, instead of being constructed with `new Symbol()`. ## Static properties The static properties are all well-known Symbols. In these Symbols' descriptions, we will use language like "`Symbol.hasInstance` is a method determining…", but bear in mind that this is referring to the semantic of an object's method having this Symbol as the method name (because well-known Symbols act as "protocols"), not describing the value of the Symbol itself. - {{jsxref("Symbol.asyncIterator")}} - : A method that returns the default AsyncIterator for an object. Used by [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of). - {{jsxref("Symbol.hasInstance")}} - : A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}. - {{jsxref("Symbol.isConcatSpreadable")}} - : A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}. - {{jsxref("Symbol.iterator")}} - : A method returning the default iterator for an object. Used by [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of). - {{jsxref("Symbol.match")}} - : A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by {{jsxref("String.prototype.match()")}}. - {{jsxref("Symbol.matchAll")}} - : A method that returns an iterator, that yields matches of the regular expression against a string. Used by {{jsxref("String.prototype.matchAll()")}}. - {{jsxref("Symbol.replace")}} - : A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}. - {{jsxref("Symbol.search")}} - : A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}. - {{jsxref("Symbol.species")}} - : A constructor function that is used to create derived objects. - {{jsxref("Symbol.split")}} - : A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}. - {{jsxref("Symbol.toPrimitive")}} - : A method converting an object to a primitive value. - {{jsxref("Symbol.toStringTag")}} - : A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}. - {{jsxref("Symbol.unscopables")}} - : An object value of whose own and inherited property names are excluded from the [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) environment bindings of the associated object. ## Static methods - {{jsxref("Symbol.for()")}} - : Searches for existing Symbols with the given `key` and returns it if found. Otherwise a new Symbol gets created in the global Symbol registry with `key`. - {{jsxref("Symbol.keyFor()")}} - : Retrieves a shared Symbol key from the global Symbol registry for the given Symbol. ## Instance properties These properties are defined on `Symbol.prototype` and shared by all `Symbol` instances. - {{jsxref("Object/constructor", "Symbol.prototype.constructor")}} - : The constructor function that created the instance object. For `Symbol` instances, the initial value is the {{jsxref("Symbol/Symbol", "Symbol")}} constructor. - {{jsxref("Symbol.prototype.description")}} - : A read-only string containing the description of the Symbol. - `Symbol.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Symbol"`. This property is used in {{jsxref("Object.prototype.toString()")}}. However, because `Symbol` also has its own [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toString) method, this property is not used unless you call [`Object.prototype.toString.call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) with a symbol as `thisArg`. ## Instance methods - {{jsxref("Symbol.prototype.toString()")}} - : Returns a string containing the description of the Symbol. Overrides the {{jsxref("Object.prototype.toString()")}} method. - {{jsxref("Symbol.prototype.valueOf()")}} - : Returns the Symbol. Overrides the {{jsxref("Object.prototype.valueOf()")}} method. - [`Symbol.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) - : Returns the Symbol. ## Examples ### Using the typeof operator with Symbols The {{jsxref("Operators/typeof", "typeof")}} operator can help you to identify Symbols. ```js typeof Symbol() === "symbol"; typeof Symbol("foo") === "symbol"; typeof Symbol.iterator === "symbol"; ``` ### Symbol type conversions Some things to note when working with type conversion of Symbols. - When trying to convert a Symbol to a number, a {{jsxref("TypeError")}} will be thrown (e.g. `+sym` or `sym | 0`). - When using loose equality, `Object(sym) == sym` returns `true`. - `Symbol("foo") + "bar"` throws a {{jsxref("TypeError")}} (can't convert Symbol to string). This prevents you from silently creating a new string property name from a Symbol, for example. - The ["safer" `String(sym)` conversion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_conversion) works like a call to {{jsxref("Symbol.prototype.toString()")}} with Symbols, but note that `new String(sym)` will throw. ### Symbols and for...in iteration Symbols are not enumerable in [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) iterations. In addition, {{jsxref("Object.getOwnPropertyNames()")}} will not return Symbol object properties, however, you can use {{jsxref("Object.getOwnPropertySymbols()")}} to get these. ```js const obj = {}; obj[Symbol("a")] = "a"; obj[Symbol.for("b")] = "b"; obj["c"] = "c"; obj.d = "d"; for (const i in obj) { console.log(i); } // "c" "d" ``` ### Symbols and JSON.stringify() Symbol-keyed properties will be completely ignored when using `JSON.stringify()`: ```js JSON.stringify({ [Symbol("foo")]: "foo" }); // '{}' ``` For more details, see {{jsxref("JSON.stringify()")}}. ### Symbol wrapper objects as property keys When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped Symbol: ```js const sym = Symbol("foo"); const obj = { [sym]: 1 }; obj[sym]; // 1 obj[Object(sym)]; // still 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Operators/typeof", "typeof")}} - [JavaScript data types and data structures](/en-US/docs/Web/JavaScript/Data_structures) - [ES6 In Depth: Symbols](https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/) on hacks.mozilla.org (2015)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/matchall/index.md
--- title: Symbol.matchAll slug: Web/JavaScript/Reference/Global_Objects/Symbol/matchAll page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.matchAll --- {{JSRef}} The **`Symbol.matchAll`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@matchAll`. The {{jsxref("String.prototype.matchAll()")}} method looks up this symbol on its first argument for the method that returns an iterator, that yields matches of the current object against a string. For more information, see [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll) and {{jsxref("String.prototype.matchAll()")}}. {{EmbedInteractiveExample("pages/js/symbol-matchall.html")}} ## Value The well-known symbol `@@matchAll`. {{js_property_attributes(0, 0, 0)}} ## Examples ### Using Symbol.matchAll ```js const str = "2016-01-02|2019-03-07"; const numbers = { *[Symbol.matchAll](str) { for (const n of str.matchAll(/[0-9]+/g)) yield n[0]; }, }; console.log(Array.from(str.matchAll(numbers))); // ["2016", "01", "02", "2019", "03", "07"] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.matchAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.match")}} - {{jsxref("Symbol.replace")}} - {{jsxref("Symbol.search")}} - {{jsxref("Symbol.split")}} - {{jsxref("String.prototype.matchAll()")}} - [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/match/index.md
--- title: Symbol.match slug: Web/JavaScript/Reference/Global_Objects/Symbol/match page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.match --- {{JSRef}} The **`Symbol.match`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@match`. The {{jsxref("String.prototype.match()")}} method looks up this symbol on its first argument for the method used to match an input string against the current object. This symbol is also used to determine if an object should be [treated as a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For more information, see [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match) and {{jsxref("String.prototype.match()")}}. {{EmbedInteractiveExample("pages/js/symbol-match.html", "taller")}} ## Value The well-known symbol `@@match`. {{js_property_attributes(0, 0, 0)}} ## Description This function is also used to identify [if objects have the behavior of regular expressions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). For example, the methods {{jsxref("String.prototype.startsWith()")}}, {{jsxref("String.prototype.endsWith()")}} and {{jsxref("String.prototype.includes()")}}, check if their first argument is a regular expression and will throw a {{jsxref("TypeError")}} if they are. Now, if the `match` symbol is set to `false` (or a [Falsy](/en-US/docs/Glossary/Falsy) value except `undefined`), it indicates that the object is not intended to be used as a regular expression object. ## Examples ### Marking a RegExp as not a regex The following code will throw a {{jsxref("TypeError")}}: ```js "/bar/".startsWith(/bar/); // Throws TypeError, as /bar/ is a regular expression // and Symbol.match is not modified. ``` However, if you set `Symbol.match` to `false`, the object will be considered as [not a regular expression object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes). The methods `startsWith` and `endsWith` won't throw a `TypeError` as a consequence. ```js const re = /foo/; re[Symbol.match] = false; "/foo/".startsWith(re); // true "/baz/".endsWith(re); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.match` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.matchAll")}} - {{jsxref("Symbol.replace")}} - {{jsxref("Symbol.search")}} - {{jsxref("Symbol.split")}} - {{jsxref("String.prototype.match()")}} - [`RegExp.prototype[@@match]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/symbol/index.md
--- title: Symbol() constructor slug: Web/JavaScript/Reference/Global_Objects/Symbol/Symbol page-type: javascript-constructor browser-compat: javascript.builtins.Symbol.Symbol --- {{JSRef}} The **`Symbol()`** function returns primitive values of type Symbol. {{EmbedInteractiveExample("pages/js/symbol-constructor.html", "taller")}} ## Syntax ```js-nolint Symbol() Symbol(description) ``` > **Note:** `Symbol()` can only be called without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to construct it with `new` throws a {{jsxref("TypeError")}}. ### Parameters - `description` {{optional_inline}} - : A string. A description of the symbol which can be used for debugging but not to access the symbol itself. ## Examples ### Creating symbols To create a new primitive symbol, you write `Symbol()` with an optional string as its description: ```js const sym1 = Symbol(); const sym2 = Symbol("foo"); const sym3 = Symbol("foo"); ``` The above code creates three new symbols. Note that `Symbol("foo")` does not coerce the string `"foo"` into a symbol. It creates a new symbol each time: ```js Symbol("foo") === Symbol("foo"); // false ``` ### new Symbol() The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}: ```js example-bad const sym = new Symbol(); // TypeError ``` This prevents authors from creating an explicit `Symbol` wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, `new Boolean`, `new String` and `new Number`). If you really want to create a `Symbol` wrapper object, you can use the `Object()` function: ```js const sym = Symbol("foo"); const symObj = Object(sym); typeof sym; // "symbol" typeof symObj; // "object" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/tostring/index.md
--- title: Symbol.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Symbol/toString page-type: javascript-instance-method browser-compat: javascript.builtins.Symbol.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("Symbol")}} values returns a string representing this symbol value. {{EmbedInteractiveExample("pages/js/symbol-prototype-tostring.html")}} ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string representing the specified symbol value. ## Description The {{jsxref("Symbol")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit {{jsxref("Object.prototype.toString()")}}. For `Symbol` values, the `toString` method returns a descriptive string in the form `"Symbol(description)"`, where `description` is the symbol's [description](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description). The `toString()` method requires its `this` value to be a `Symbol` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to symbol values. Because `Symbol` has a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) method, that method always takes priority over `toString()` when a `Symbol` object is [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, because `Symbol.prototype[@@toPrimitive]()` returns a symbol primitive, and symbol primitives throw a {{jsxref("TypeError")}} when implicitly converted to a string, the `toString()` method is never implicitly called by the language. To stringify a symbol, you must explicitly call its `toString()` method or use the [`String()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String#using_string_to_stringify_a_symbol) function. ## Examples ### Using toString() ```js Symbol("desc").toString(); // "Symbol(desc)" // well-known symbols Symbol.iterator.toString(); // "Symbol(Symbol.iterator)" // global symbols Symbol.for("foo").toString(); // "Symbol(foo)" ``` ### Implicitly calling toString() The only way to make JavaScript implicitly call `toString()` instead of [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) on a symbol wrapper object is by [deleting](/en-US/docs/Web/JavaScript/Reference/Operators/delete) the `@@toPrimitive` method first. > **Warning:** You should not do this in practice. Never mutate built-in objects unless you know exactly what you're doing. ```js delete Symbol.prototype[Symbol.toPrimitive]; console.log(`${Object(Symbol("foo"))}`); // "Symbol(foo)" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/toprimitive/index.md
--- title: Symbol.toPrimitive slug: Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.toPrimitive --- {{JSRef}} The **`Symbol.toPrimitive`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@toPrimitive`. All [type coercion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion) algorithms look up this symbol on objects for the method that accepts a preferred type and returns a primitive representation of the object, before falling back to using the object's `valueOf()` and `toString()` methods. {{EmbedInteractiveExample("pages/js/symbol-toprimitive.html")}} ## Value The well-known symbol `@@toPrimitive`. {{js_property_attributes(0, 0, 0)}} ## Description With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`. The `"number"` hint is used by [numeric coercion](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) algorithms. The `"string"` hint is used by the [string coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) algorithm. The `"default"` hint is used by the [primitive coercion](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as [`Symbol.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) does). The language does not enforce alignment between the `hint` and the result type, although `[@@toPrimitive]()` must return a primitive, or a {{jsxref("TypeError")}} is thrown. Objects without the `@@toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the [type coercion](/en-US/docs/Web/JavaScript/Data_structures#type_coercion) section. `@@toPrimitive` allows full control over the primitive conversion process. For example, [`Date.prototype[@@toPrimitive]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) treats `"default"` as if it's `"string"` and calls `toString()` instead of `valueOf()`. [`Symbol.prototype[@@toPrimitive]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) ignores the hint and always returns a symbol, which means even in string contexts, {{jsxref("Symbol.prototype.toString()")}} won't be called, and `Symbol` objects must always be explicitly converted to strings through [`String()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String). ## Examples ### Modifying primitive values converted from an object Following example describes how `Symbol.toPrimitive` property can modify the primitive value converted from an object. ```js // An object without Symbol.toPrimitive property. const obj1 = {}; console.log(+obj1); // NaN console.log(`${obj1}`); // "[object Object]" console.log(obj1 + ""); // "[object Object]" // An object with Symbol.toPrimitive property. const obj2 = { [Symbol.toPrimitive](hint) { if (hint === "number") { return 10; } if (hint === "string") { return "hello"; } return true; }, }; console.log(+obj2); // 10 — hint is "number" console.log(`${obj2}`); // "hello" — hint is "string" console.log(obj2 + ""); // "true" — hint is "default" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.toPrimitive` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - [`Date.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) - [`Symbol.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive) - {{jsxref("Object.prototype.toString()")}} - {{jsxref("Object.prototype.valueOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/@@toprimitive/index.md
--- title: Symbol.prototype[@@toPrimitive]() slug: Web/JavaScript/Reference/Global_Objects/Symbol/@@toPrimitive page-type: javascript-instance-method browser-compat: javascript.builtins.Symbol.@@toPrimitive --- {{JSRef}} The **`[@@toPrimitive]()`** method of {{jsxref("Symbol")}} values returns this symbol value. ## Syntax ```js-nolint symbolValue[Symbol.toPrimitive](hint) ``` ### Parameters - `hint` - : A string value indicating the primitive value to return. The value is ignored. ### Return value The primitive value of the specified {{jsxref("Symbol")}} object. ## Description The `[@@toPrimitive]()` method of {{jsxref("Symbol")}} returns the primitive value of a Symbol object as a Symbol data type. The `hint` argument is not used. JavaScript calls the `[@@toPrimitive]()` method to convert an object to a primitive value. You rarely need to invoke the `[@@toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ## Examples ### Using @@toPrimitive ```js const sym = Symbol("example"); sym === sym[Symbol.toPrimitive](); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Symbol.toPrimitive")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/search/index.md
--- title: Symbol.search slug: Web/JavaScript/Reference/Global_Objects/Symbol/search page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.search --- {{JSRef}} The **`Symbol.search`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@search`. The {{jsxref("String.prototype.search()")}} method looks up this symbol on its first argument for the method that returns the index within a string that matches the current object. For more information, see [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search) and {{jsxref("String.prototype.search()")}}. {{EmbedInteractiveExample("pages/js/symbol-search.html")}} ## Value The well-known symbol `@@search`. {{js_property_attributes(0, 0, 0)}} ## Examples ### Custom string search ```js class caseInsensitiveSearch { constructor(value) { this.value = value.toLowerCase(); } [Symbol.search](string) { return string.toLowerCase().indexOf(this.value); } } console.log("foobar".search(new caseInsensitiveSearch("BaR"))); // 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.search` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.match")}} - {{jsxref("Symbol.matchAll")}} - {{jsxref("Symbol.replace")}} - {{jsxref("Symbol.split")}} - {{jsxref("String.prototype.search()")}} - [`RegExp.prototype[@@search]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/split/index.md
--- title: Symbol.split slug: Web/JavaScript/Reference/Global_Objects/Symbol/split page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.split --- {{JSRef}} The **`Symbol.split`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@split`. The {{jsxref("String.prototype.split()")}} method looks up this symbol on its first argument for the method that splits a string at the indices that match the current object. For more information, see[`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split) and {{jsxref("String.prototype.split()")}}. {{EmbedInteractiveExample("pages/js/symbol-split.html", "taller")}} ## Value The well-known symbol `@@split`. {{js_property_attributes(0, 0, 0)}} ## Examples ### Custom reverse split ```js class ReverseSplit { [Symbol.split](string) { const array = string.split(" "); return array.reverse(); } } console.log("Another one bites the dust".split(new ReverseSplit())); // [ "dust", "the", "bites", "one", "Another" ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.split` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.match")}} - {{jsxref("Symbol.matchAll")}} - {{jsxref("Symbol.replace")}} - {{jsxref("Symbol.search")}} - {{jsxref("String.prototype.split()")}} - [`RegExp.prototype[@@split]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/hasinstance/index.md
--- title: Symbol.hasInstance slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.hasInstance --- {{JSRef}} The **`Symbol.hasInstance`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@hasInstance`. The {{jsxref("Operators/instanceof", "instanceof")}} operator looks up this symbol on its right-hand operand for the method used to determine if the constructor object recognizes an object as its instance. {{EmbedInteractiveExample("pages/js/symbol-hasinstance.html")}} ## Value The well-known symbol `@@hasInstance`. {{js_property_attributes(0, 0, 0)}} ## Description The `instanceof` operator uses the following algorithm to calculate the return value of `object instanceof constructor`: 1. If `constructor` has a `@@hasInstance` method, then call it with `object` as the first argument and return the result, [coerced to a boolean](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). Throw a {{jsxref("TypeError")}} if `constructor` is not an object, or if `constructor[@@hasInstance]` is not one of `null`, `undefined`, or a function. 2. Otherwise, if `constructor` doesn't have a `@@hasInstance` method (`constructor[@@hasInstance]` is `null` or `undefined`), then determine the result using the same algorithm as [`Function.prototype[@@hasInstance]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance). Throw a {{jsxref("TypeError")}} if `constructor` is not a function. Because all functions inherit from `Function.prototype` by default, most of the time, the [`Function.prototype[@@hasInstance]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance) method specifies the behavior of `instanceof` when the right-hand side is a function. ## Examples ### Custom instanceof behavior You could implement your custom `instanceof` behavior like this, for example: ```js class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance); } } console.log([] instanceof MyArray); // true ``` ```js function MyArray() {} Object.defineProperty(MyArray, Symbol.hasInstance, { value(instance) { return Array.isArray(instance); }, }); console.log([] instanceof MyArray); // true ``` ### Checking the instance of an object Just in the same manner at which you can check if an object is an instance of a class using the `instanceof` keyword, we can also use `Symbol.hasInstance` for such checks. ```js class Animal { constructor() {} } const cat = new Animal(); console.log(Animal[Symbol.hasInstance](cat)); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Operators/instanceof", "instanceof")}} - [`Function.prototype[@@hasInstance]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/description/index.md
--- title: Symbol.prototype.description slug: Web/JavaScript/Reference/Global_Objects/Symbol/description page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.Symbol.description --- {{JSRef}} The **`description`** accessor property of {{jsxref("Symbol")}} values returns a string containing the description of this symbol, or `undefined` if the symbol has no description. {{EmbedInteractiveExample("pages/js/symbol-prototype-description.html")}} ## Description {{jsxref("Symbol")}} objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples. ## Examples ### Using description ```js Symbol("desc").toString(); // "Symbol(desc)" Symbol("desc").description; // "desc" Symbol("").description; // "" Symbol().description; // undefined // well-known symbols Symbol.iterator.toString(); // "Symbol(Symbol.iterator)" Symbol.iterator.description; // "Symbol.iterator" // global symbols Symbol.for("foo").toString(); // "Symbol(foo)" Symbol.for("foo").description; // "foo" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.prototype.description` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/species/index.md
--- title: Symbol.species slug: Web/JavaScript/Reference/Global_Objects/Symbol/species page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.species --- {{JSRef}} The **`Symbol.species`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@species`. Methods that create copies of an object may look up this symbol on the object for the constructor function to use when creating the copy. > **Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. {{EmbedInteractiveExample("pages/js/symbol-species.html")}} ## Value The well-known symbol `@@species`. {{js_property_attributes(0, 0, 0)}} ## Description The `@@species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as {{jsxref("Array/map", "map()")}}. the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. For more information, see [subclassing built-ins](/en-US/docs/Web/JavaScript/Reference/Classes/extends#subclassing_built-ins). All built-in implementations of `@@species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array. ## Examples ### Using species You might want to return {{jsxref("Array")}} objects in your derived array class `MyArray`. For example, when using methods such as {{jsxref("Array/map", "map()")}} that return the default constructor, you want these methods to return a parent `Array` object, instead of the `MyArray` object. The `species` symbol lets you do this: ```js class MyArray extends Array { // Overwrite species to the parent Array constructor static get [Symbol.species]() { return Array; } } const a = new MyArray(1, 2, 3); const mapped = a.map((x) => x * x); console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Array/@@species", "Array[@@species]")}} - {{jsxref("ArrayBuffer/@@species", "ArrayBuffer[@@species]")}} - {{jsxref("Map/@@species", "Map[@@species]")}} - {{jsxref("Promise/@@species", "Promise[@@species]")}} - {{jsxref("RegExp/@@species", "RegExp[@@species]")}} - {{jsxref("Set/@@species", "Set[@@species]")}} - {{jsxref("TypedArray/@@species", "TypedArray[@@species]")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/iterator/index.md
--- title: Symbol.iterator slug: Web/JavaScript/Reference/Global_Objects/Symbol/iterator page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.iterator --- {{JSRef}} The **`Symbol.iterator`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@iterator`. The [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) looks up this symbol for the method that returns the iterator for an object. In order for an object to be iterable, it must have an `@@iterator` key. {{EmbedInteractiveExample("pages/js/symbol-iterator.html")}} ## Value The well-known symbol `@@iterator`. {{js_property_attributes(0, 0, 0)}} ## Description Whenever an object needs to be iterated (such as at the beginning of a `for...of` loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. Some built-in types have a default iteration behavior, while other types (such as {{jsxref("Object")}}) do not. Some built-in types with a `@@iterator` method are: - [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - [`String.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) - [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator) - [`Set.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator) See also [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for more information. ## Examples ### User-defined iterables We can make our own iterables like this: ```js const myIterable = {}; myIterable[Symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myIterable]; // [1, 2, 3] ``` Or iterables can be defined directly inside a class or object using a [computed property](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names): ```js class Foo { *[Symbol.iterator]() { yield 1; yield 2; yield 3; } } const someObj = { *[Symbol.iterator]() { yield "a"; yield "b"; }, }; console.log(...new Foo()); // 1, 2, 3 console.log(...someObj); // 'a', 'b' ``` ### Non-well-formed iterables If an iterable's `@@iterator` method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior: ```js example-bad const nonWellFormedIterable = {}; nonWellFormedIterable[Symbol.iterator] = () => 1; [...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.iterator` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) - [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - [`String.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) - [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator) - [`Set.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator) - [`arguments[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator) - [`Segments.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/@@iterator)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/tostringtag/index.md
--- title: Symbol.toStringTag slug: Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.toStringTag --- {{JSRef}} The **`Symbol.toStringTag`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@toStringTag`. {{jsxref("Object.prototype.toString()")}} looks up this symbol on the `this` value for the property containing a string that represents the type of the object. {{EmbedInteractiveExample("pages/js/symbol-tostringtag.html")}} ## Value The well-known symbol `@@toStringTag`. {{js_property_attributes(0, 0, 0)}} ## Examples ### Default tags Some values do not have `Symbol.toStringTag`, but have special `toString()` representations. For a complete list, see {{jsxref("Object.prototype.toString()")}}. ```js Object.prototype.toString.call("foo"); // "[object String]" Object.prototype.toString.call([1, 2]); // "[object Array]" Object.prototype.toString.call(3); // "[object Number]" Object.prototype.toString.call(true); // "[object Boolean]" Object.prototype.toString.call(undefined); // "[object Undefined]" Object.prototype.toString.call(null); // "[object Null]" // ... and more ``` ### Built-in toStringTag symbols Most built-in objects provide their own `@@toStringTag` property. Almost all built-in objects' `@@toStringTag` property is not writable, not enumerable, and configurable; the exception is {{jsxref("Iterator")}}, which is writable for compatibility reasons. For constructor objects like {{jsxref("Promise")}}, the property is installed on `Constructor.prototype`, so that all instances of the constructor inherit `@@toStringTag` and can be stringified. For non-constructor objects like {{jsxref("Math")}} and {{jsxref("JSON")}}, the property is installed as a static property, so that the namespace object itself can be stringified. Sometimes, the constructor also provides its own `toString` method (for example, {{jsxref("Intl.Locale")}}), in which case the `@@toStringTag` property is only used when you explicitly call `Object.prototype.toString` on it. ```js Object.prototype.toString.call(new Map()); // "[object Map]" Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolve()); // "[object Promise]" // ... and more ``` ### Custom tag with toStringTag When creating your own class, JavaScript defaults to the "Object" tag: ```js class ValidatorClass {} Object.prototype.toString.call(new ValidatorClass()); // "[object Object]" ``` Now, with the help of `toStringTag`, you are able to set your own custom tag: ```js class ValidatorClass { get [Symbol.toStringTag]() { return "Validator"; } } Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]" ``` ### toStringTag available on all DOM prototype objects Due to a [WebIDL spec change](https://github.com/whatwg/webidl/pull/357) in mid-2020, browsers are adding a `Symbol.toStringTag` property to all DOM prototype objects. For example, to access the `Symbol.toStringTag` property on {{domxref("HTMLButtonElement")}}: ```js const test = document.createElement("button"); test.toString(); // "[object HTMLButtonElement]" test[Symbol.toStringTag]; // "HTMLButtonElement" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.toStringTag` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Object.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/for/index.md
--- title: Symbol.for() slug: Web/JavaScript/Reference/Global_Objects/Symbol/for page-type: javascript-static-method browser-compat: javascript.builtins.Symbol.for --- {{JSRef}} The **`Symbol.for()`** static method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key. {{EmbedInteractiveExample("pages/js/symbol-for.html")}} ## Syntax ```js-nolint Symbol.for(key) ``` ### Parameters - `key` - : String, required. The key for the symbol (and also used for the description of the symbol). ### Return value An existing symbol with the given key if found; otherwise, a new symbol is created and returned. ## Description In contrast to `Symbol()`, the `Symbol.for()` function creates a symbol available in a [global symbol registry](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) list. `Symbol.for()` does also not necessarily create a new symbol on every call, but checks first if a symbol with the given `key` is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, `Symbol.for()` will create a new global symbol. ## Examples ### Using Symbol.for() ```js Symbol.for("foo"); // create a new global symbol Symbol.for("foo"); // retrieve the already created symbol // Same global symbol, but not locally Symbol.for("bar") === Symbol.for("bar"); // true Symbol("bar") === Symbol("bar"); // false // The key is also used as the description const sym = Symbol.for("mario"); sym.toString(); // "Symbol(mario)" ``` To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: ```js Symbol.for("mdn.foo"); Symbol.for("mdn.bar"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Symbol.keyFor()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/replace/index.md
--- title: Symbol.replace slug: Web/JavaScript/Reference/Global_Objects/Symbol/replace page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.replace --- {{JSRef}} The **`Symbol.replace`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@replace`. The {{jsxref("String.prototype.replace()")}} method looks up this symbol on its first argument for the method that replaces substrings matched by the current object. For more information, see [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace) and {{jsxref("String.prototype.replace()")}}. {{EmbedInteractiveExample("pages/js/symbol-replace.html")}} ## Value The well-known symbol `@@replace`. {{js_property_attributes(0, 0, 0)}} ## Examples ### Using Symbol.replace ```js class CustomReplacer { constructor(value) { this.value = value; } [Symbol.replace](string) { return string.replace(this.value, "#!@?"); } } console.log("football".replace(new CustomReplacer("foo"))); // "#!@?tball" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.replace` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Symbol.match")}} - {{jsxref("Symbol.matchAll")}} - {{jsxref("Symbol.search")}} - {{jsxref("Symbol.split")}} - {{jsxref("String.prototype.replace()")}} - [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/keyfor/index.md
--- title: Symbol.keyFor() slug: Web/JavaScript/Reference/Global_Objects/Symbol/keyFor page-type: javascript-static-method browser-compat: javascript.builtins.Symbol.keyFor --- {{JSRef}} The **`Symbol.keyFor()`** static method retrieves a shared symbol key from the global symbol registry for the given symbol. {{EmbedInteractiveExample("pages/js/symbol-keyfor.html")}} ## Syntax ```js-nolint Symbol.keyFor(sym) ``` ### Parameters - `sym` - : Symbol, required. The symbol to find a key for. ### Return value A string representing the key for the given symbol if one is found on the [global registry](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry); otherwise, {{jsxref("undefined")}}. ## Examples ### Using keyFor() ```js const globalSym = Symbol.for("foo"); // create a new global symbol Symbol.keyFor(globalSym); // "foo" const localSym = Symbol(); Symbol.keyFor(localSym); // undefined // well-known symbols are not symbols registered // in the global symbol registry Symbol.keyFor(Symbol.iterator); // undefined ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Symbol.for()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/valueof/index.md
--- title: Symbol.prototype.valueOf() slug: Web/JavaScript/Reference/Global_Objects/Symbol/valueOf page-type: javascript-instance-method browser-compat: javascript.builtins.Symbol.valueOf --- {{JSRef}} The **`valueOf()`** method of {{jsxref("Symbol")}} values returns this symbol value. {{EmbedInteractiveExample("pages/js/symbol-prototype-valueof.html")}} ## Syntax ```js-nolint valueOf() ``` ### Parameters None. ### Return value The primitive value of the specified {{jsxref("Symbol")}} object. ## Description The `valueOf()` method of {{jsxref("Symbol")}} returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the `valueOf()` method to convert an object to a primitive value. You rarely need to invoke the `valueOf()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. ## Examples ### Using valueOf() ```js const sym = Symbol("example"); sym === sym.valueOf(); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.valueOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/isconcatspreadable/index.md
--- title: Symbol.isConcatSpreadable slug: Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.isConcatSpreadable --- {{JSRef}} The **`Symbol.isConcatSpreadable`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@isConcatSpreadable`. The {{jsxref("Array.prototype.concat()")}} method looks up this symbol on each object being concatenated to determine if it should be treated as an array-like object and flattened to its array elements. {{EmbedInteractiveExample("pages/js/symbol-isconcatspreadable.html")}} ## Value The well-known symbol `@@isConcatSpreadable`. {{js_property_attributes(0, 0, 0)}} ## Description The `@@isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. - For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. ## Examples ### Arrays By default, {{jsxref("Array.prototype.concat()")}} spreads (flattens) arrays into its result: ```js const alpha = ["a", "b", "c"]; const numeric = [1, 2, 3]; const alphaNumeric = alpha.concat(numeric); console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3] ``` When setting `Symbol.isConcatSpreadable` to `false`, you can disable the default behavior: ```js const alpha = ["a", "b", "c"]; const numeric = [1, 2, 3]; numeric[Symbol.isConcatSpreadable] = false; const alphaNumeric = alpha.concat(numeric); console.log(alphaNumeric); // Result: ['a', 'b', 'c', [1, 2, 3] ] ``` ### Array-like objects For array-like objects, the default is to not spread. `Symbol.isConcatSpreadable` needs to be set to `true` in order to get a flattened array: ```js const x = [1, 2, 3]; const fakeArray = { [Symbol.isConcatSpreadable]: true, length: 2, 0: "hello", 1: "world", }; x.concat(fakeArray); // [1, 2, 3, "hello", "world"] ``` > **Note:** The `length` property is used to control the number of object properties to be added. In the above example, `length:2` indicates two properties has to be added. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Symbol.isConcatSpreadable` in `core-js`](https://github.com/zloirock/core-js#ecmascript-symbol) - {{jsxref("Array.prototype.concat()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/asynciterator/index.md
--- title: Symbol.asyncIterator slug: Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.asyncIterator --- {{JSRef}} The **`Symbol.asyncIterator`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@asyncIterator`. The [async iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) looks up this symbol for the method that returns the async iterator for an object. In order for an object to be async iterable, it must have an `@@asyncIterator` key. {{EmbedInteractiveExample("pages/js/symbol-asynciterator.html", "taller")}} ## Value The well-known symbol `@@asyncIterator`. {{js_property_attributes(0, 0, 0)}} ## Examples ### User-defined async iterables You can define your own async iterable by setting the `[Symbol.asyncIterator]` property on an object. ```js const myAsyncIterable = { async *[Symbol.asyncIterator]() { yield "hello"; yield "async"; yield "iteration!"; }, }; (async () => { for await (const x of myAsyncIterable) { console.log(x); } })(); // Logs: // "hello" // "async" // "iteration!" ``` When creating an API, remember that async iterables are designed to represent something _iterable_ — like a stream of data or a list —, not to completely replace callbacks and events in most situations. ### Built-in async iterables There is no object in the core JavaScript language that is async iterable. Some web APIs, such as {{domxref("ReadableStream")}}, have the `Symbol.asyncIterator` method set by default. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) - [for await...of](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol
data/mdn-content/files/en-us/web/javascript/reference/global_objects/symbol/unscopables/index.md
--- title: Symbol.unscopables slug: Web/JavaScript/Reference/Global_Objects/Symbol/unscopables page-type: javascript-static-data-property browser-compat: javascript.builtins.Symbol.unscopables --- {{JSRef}} The **`Symbol.unscopables`** static data property represents the [well-known symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols) `@@unscopables`. The {{jsxref("Statements/with", "with")}} statement looks up this symbol on the scope object for a property containing a collection of properties that should not become bindings within the `with` environment. {{EmbedInteractiveExample("pages/js/symbol-unscopables.html")}} ## Value The well-known symbol `@@unscopables`. {{js_property_attributes(0, 0, 0)}} ## Description The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) environment bindings. Note that when using [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), `with` statements are not available, and this symbol is likely not needed. Setting a property of the `@@unscopables` object to `true` (or any [truthy](/en-US/docs/Glossary/Truthy) value) will make the corresponding property of the `with` scope object _unscopable_ and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any [falsy](/en-US/docs/Glossary/Falsy) value) will make it _scopable_ and thus appear as lexical scope variables. When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like [`toString`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see [an example below](#avoid_using_a_non-null-prototype_object_as_unscopables)). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like [`Array.prototype[@@unscopables]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@unscopables) does. This protocol is also utilized by DOM APIs, such as [`Element.prototype.append()`](/en-US/docs/Web/API/Element/append). ## Examples ### Scoping in with statements The following code works fine in ES5 and below. However, in ECMAScript 2015 and later, the {{jsxref("Array.prototype.keys()")}} method was introduced. That means that inside a `with` environment, "keys" would now be the method and not the variable. That's why the `@@unscopables` symbol was introduced. A built-in `@@unscopables` setting is implemented as {{jsxref("Array/@@unscopables", "Array.prototype[@@unscopables]")}} to prevent some of the Array methods being scoped into the `with` statement. ```js var keys = []; with (Array.prototype) { keys.push("something"); } ``` ### Unscopables in objects You can also set `@@unscopables` for your own objects. ```js const obj = { foo: 1, bar: 2, baz: 3, }; obj[Symbol.unscopables] = { // Make the object have `null` prototype to prevent // `Object.prototype` methods from being unscopable __proto__: null, // `foo` will be scopable foo: false, // `bar` will be unscopable bar: true, // `baz` is omitted; because `undefined` is falsy, it is also scopable (default) }; with (obj) { console.log(foo); // 1 console.log(bar); // ReferenceError: bar is not defined console.log(baz); // 3 } ``` ### Avoid using a non-null-prototype object as @@unscopables Declaring `@@unscopables` as a plain object without eliminating its prototype may cause subtle bugs. Consider the following code working before `@@unscopables`: ```js const character = { name: "Yoda", toString: function () { return "Use with statements, you must not"; }, }; with (character) { console.log(name + ' says: "' + toString() + '"'); // Yoda says: "Use with statements, you must not" } ``` To preserve backward compatibility, you decided to add an `@@unscopables` property when adding more properties to `character`. You may naïvely do it like: ```js example-bad const character = { name: "Yoda", toString: function () { return "Use with statements, you must not"; }, student: "Luke", [Symbol.unscopables]: { // Make `student` unscopable student: true, }, }; ``` However, the code above now breaks: ```js with (character) { console.log(name + ' says: "' + toString() + '"'); // Yoda says: "[object Undefined]" } ``` This is because when looking up `character[Symbol.unscopables].toString`, it returns [`Object.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString), which is a truthy value, thus making the `toString()` call in the `with()` statement reference `globalThis.toString()` instead — and because it's called without a [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), `this` is `undefined`, making it return `[object Undefined]`. Even when the method is not overridden by `character`, making it unscopable will change the value of `this`. ```js const proto = {}; const obj = { __proto__: proto }; with (proto) { console.log(isPrototypeOf(obj)); // true; `isPrototypeOf` is scoped and `this` is `proto` } proto[Symbol.unscopables] = {}; with (proto) { console.log(isPrototypeOf(obj)); // TypeError: Cannot convert undefined or null to object // `isPrototypeOf` is unscoped and `this` is undefined } ``` To fix this, always make sure `@@unscopables` only contains properties you wish to be unscopable, without `Object.prototype` properties. ```js example-good const character = { name: "Yoda", toString: function () { return "Use with statements, you must not"; }, student: "Luke", [Symbol.unscopables]: { // Make the object have `null` prototype to prevent // `Object.prototype` methods from being unscopable __proto__: null, // Make `student` unscopable student: true, }, }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Array/@@unscopables", "Array.prototype[@@unscopables]")}} - [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) - [`Element.prototype.append()`](/en-US/docs/Web/API/Element/append)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean/index.md
--- title: Boolean slug: Web/JavaScript/Reference/Global_Objects/Boolean page-type: javascript-class browser-compat: javascript.builtins.Boolean --- {{JSRef}} The **`Boolean`** object represents a truth value: `true` or `false`. ## Description ### Boolean primitives and Boolean objects For converting non-boolean values to boolean, use `Boolean` as a function or use the [double NOT](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT#double_not_!!) operator. Do not use the `Boolean()` constructor with `new`. ```js example-good const good = Boolean(expression); const good2 = !!expression; ``` ```js example-bad const bad = new Boolean(expression); // don't use this! ``` This is because _all_ objects, including a `Boolean` object whose wrapped value is `false`, are {{glossary("truthy")}} and evaluate to `true` in places such as conditional statements. (See also the [boolean coercion](#boolean_coercion) section below.) ```js if (new Boolean(true)) { console.log("This log is printed."); } if (new Boolean(false)) { console.log("This log is ALSO printed."); } const myFalse = new Boolean(false); // myFalse is a Boolean object (not the primitive value false) const g = Boolean(myFalse); // g is true const myString = new String("Hello"); // myString is a String object const s = Boolean(myString); // s is true ``` > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ### Boolean coercion Many built-in operations that expect booleans first coerce their arguments to booleans. [The operation](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-toboolean) can be summarized as follows: - Booleans are returned as-is. - [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) turns into `false`. - [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) turns into `false`. - `0`, `-0`, and `NaN` turn into `false`; other numbers turn into `true`. - `0n` turns into `false`; other [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) turn into `true`. - The empty string `""` turns into `false`; other strings turn into `true`. - [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) turn into `true`. - All objects become `true`. > **Note:** A legacy behavior makes [`document.all`](/en-US/docs/Web/API/Document/all) return `false` when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used. > **Note:** Unlike other type conversions like [string coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) or [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), boolean coercion does not attempt to convert objects to primitives. In other words, there are only a handful of values that get coerced to `false` — these are called [falsy](/en-US/docs/Glossary/Falsy) values. All other values are called [truthy](/en-US/docs/Glossary/Truthy) values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context. There are two ways to achieve the same effect in JavaScript. - [Double NOT](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT#double_not_!!): `!!x` negates `x` twice, which converts `x` to a boolean using the same algorithm as above. - The [`Boolean()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/Boolean) function: `Boolean(x)` uses the same algorithm as above to convert `x`. Note that truthiness is not the same as being [loosely equal](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) to `true` or `false`. ```js if ([]) { console.log("[] is truthy"); } if ([] == false) { console.log("[] == false"); } // [] is truthy // [] == false ``` `[]` is truthy, but it's also loosely equal to `false`. It's truthy, because all objects are truthy. However, when comparing with `false`, which is a primitive, `[]` is also converted to a primitive, which is `""` via {{jsxref("Array.prototype.toString()")}}. Comparing strings and booleans results in both being [converted to numbers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), and they both become `0`, so `[] == false` is `true`. In general, falsiness and `== false` differ in the following cases: - `NaN`, `undefined`, and `null` are falsy but not loosely equal to `false`. - `"0"` (and other string literals that are not `""` but [get coerced to 0](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion)) is truthy but loosely equal to `false`. - Objects are always truthy, but their primitive representation may be loosely equal to `false`. Truthy values are even more unlikely to be loosely equal to `true`. All values are either truthy or falsy, but most values are loosely equal to neither `true` nor `false`. ## Constructor - {{jsxref("Boolean/Boolean", "Boolean()")}} - : Creates a new `Boolean` object. ## Instance properties These properties are defined on `Boolean.prototype` and shared by all `Boolean` instances. - {{jsxref("Object/constructor", "Boolean.prototype.constructor")}} - : The constructor function that created the instance object. For `Boolean` instances, the initial value is the {{jsxref("Boolean/Boolean", "Boolean")}} constructor. ## Instance methods - {{jsxref("Boolean.prototype.toString()")}} - : Returns a string of either `true` or `false` depending upon the value of the object. Overrides the {{jsxref("Object.prototype.toString()")}} method. - {{jsxref("Boolean.prototype.valueOf()")}} - : Returns the primitive value of the {{jsxref("Boolean")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method. ## Examples ### Creating Boolean objects with an initial value of false ```js const bNoParam = new Boolean(); const bZero = new Boolean(0); const bNull = new Boolean(null); const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); ``` ### Creating Boolean objects with an initial value of true ```js const btrue = new Boolean(true); const btrueString = new Boolean("true"); const bfalseString = new Boolean("false"); const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean({}); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Boolean](/en-US/docs/Glossary/Boolean) - [Boolean primitives](/en-US/docs/Web/JavaScript/Data_structures#boolean_type) - [Boolean data type](https://en.wikipedia.org/wiki/Boolean_data_type) on Wikipedia
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean/boolean/index.md
--- title: Boolean() constructor slug: Web/JavaScript/Reference/Global_Objects/Boolean/Boolean page-type: javascript-constructor browser-compat: javascript.builtins.Boolean.Boolean --- {{JSRef}} The **`Boolean()`** constructor creates {{jsxref("Boolean")}} objects. When called as a function, it returns primitive values of type Boolean. {{EmbedInteractiveExample("pages/js/boolean-constructor.html", "shorter")}} ## Syntax ```js-nolint new Boolean(value) Boolean(value) ``` > **Note:** `Boolean()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but with different effects. See [Return value](#return_value). ### Parameters - `value` - : The initial value of the `Boolean` object. ### Return value When `Boolean()` is called as a constructor (with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new)), it creates a {{jsxref("Boolean")}} object, which is **not** a primitive. When `Boolean()` is called as a function (without `new`), it coerces the parameter to a boolean primitive. > **Warning:** You should rarely find yourself using `Boolean` as a constructor. ## Description The value passed as the first parameter is [converted to a boolean value](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#boolean_coercion). If the value is omitted or is `0`, `-0`, `0n`, [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), `false`, {{jsxref("NaN")}}, {{jsxref("undefined")}}, or the empty string (`""`), then the object has an initial value of `false`. All other values, including any object, an empty array (`[]`), or the string `"false"`, create an object with an initial value of `true`. > **Note:** When the non-standard property [`document.all`](/en-US/docs/Web/API/Document/all) is used as an argument for this constructor, the result is a `Boolean` object with the value `false`. This property is legacy and non-standard and should not be used. ## Examples ### Creating Boolean objects with an initial value of false ```js const bZero = new Boolean(0); const bNull = new Boolean(null); const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); typeof bfalse; // "object" Boolean(bfalse); // true ``` Note how converting a `Boolean` object to a primitive with `Boolean()` always yields `true`, even if the object holds a value of `false`. You are therefore always advised to avoid constructing `Boolean` wrapper objects. If you need to take the primitive value out from the wrapper object, instead of using the `Boolean()` function, use the object's [`valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/valueOf) method instead. ```js const bfalse = new Boolean(false); bfalse.valueOf(); // false ``` ### Creating `Boolean` objects with an initial value of `true` ```js const btrue = new Boolean(true); const btrueString = new Boolean("true"); const bfalseString = new Boolean("false"); const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean({}); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Boolean](/en-US/docs/Glossary/Boolean)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean/tostring/index.md
--- title: Boolean.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Boolean/toString page-type: javascript-instance-method browser-compat: javascript.builtins.Boolean.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("Boolean")}} values returns a string representing the specified boolean value. {{EmbedInteractiveExample("pages/js/boolean-tostring.html")}} ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string representing the specified boolean value. ## Description The {{jsxref("Boolean")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit {{jsxref("Object.prototype.toString()")}}. For `Boolean` values, the `toString` method returns a string representation of the boolean value, which is either `"true"` or `"false"`. The `toString()` method requires its `this` value to be a `Boolean` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to boolean values. Because `Boolean` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `Boolean` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, boolean _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Boolean.prototype.toString = () => "Overridden"; console.log(`${true}`); // "true" console.log(`${new Boolean(true)}`); // "Overridden" ``` ## Examples ### Using toString() ```js const flag = new Boolean(true); console.log(flag.toString()); // "true" console.log(false.toString()); // "false" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean
data/mdn-content/files/en-us/web/javascript/reference/global_objects/boolean/valueof/index.md
--- title: Boolean.prototype.valueOf() slug: Web/JavaScript/Reference/Global_Objects/Boolean/valueOf page-type: javascript-instance-method browser-compat: javascript.builtins.Boolean.valueOf --- {{JSRef}} The **`valueOf()`** method of {{jsxref("Boolean")}} values returns the primitive value of a {{jsxref("Boolean")}} object. {{EmbedInteractiveExample("pages/js/boolean-valueof.html")}} ## Syntax ```js-nolint valueOf() ``` ### Parameters None. ### Return value The primitive value of the given {{jsxref("Boolean")}} object. ## Description The `valueOf()` method of {{jsxref("Boolean")}} returns the primitive value of a `Boolean` object or literal `Boolean` as a Boolean data type. This method is usually called internally by JavaScript and not explicitly in code. ## Examples ### Using `valueOf()` ```js x = new Boolean(); myVar = x.valueOf(); // assigns false to myVar ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.valueOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/index.md
--- title: Proxy slug: Web/JavaScript/Reference/Global_Objects/Proxy page-type: javascript-class browser-compat: javascript.builtins.Proxy --- {{JSRef}} The **`Proxy`** object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object. ## Description The `Proxy` object allows you to create an object that can be used in place of the original object, but which may redefine fundamental `Object` operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on. You create a `Proxy` with two parameters: - `target`: the original object which you want to proxy - `handler`: an object that defines which operations will be intercepted and how to redefine intercepted operations. For example, this code creates a proxy for the `target` object. ```js const target = { message1: "hello", message2: "everyone", }; const handler1 = {}; const proxy1 = new Proxy(target, handler1); ``` Because the handler is empty, this proxy behaves just like the original target: ```js console.log(proxy1.message1); // hello console.log(proxy1.message2); // everyone ``` To customize the proxy, we define functions on the handler object: ```js const target = { message1: "hello", message2: "everyone", }; const handler2 = { get(target, prop, receiver) { return "world"; }, }; const proxy2 = new Proxy(target, handler2); ``` Here we've provided an implementation of the {{jsxref("Proxy/Proxy/get", "get()")}} handler, which intercepts attempts to access properties in the target. Handler functions are sometimes called _traps_, presumably because they trap calls to the target object. The very simple trap in `handler2` above redefines all property accessors: ```js console.log(proxy2.message1); // world console.log(proxy2.message2); // world ``` Proxies are often used with the {{jsxref("Reflect")}} object, which provides some methods with the same names as the `Proxy` traps. The `Reflect` methods provide the reflective semantics for invoking the corresponding [object internal methods](#object_internal_methods). For example, we can call `Reflect.get` if we don't wish to redefine the object's behavior: ```js const target = { message1: "hello", message2: "everyone", }; const handler3 = { get(target, prop, receiver) { if (prop === "message2") { return "world"; } return Reflect.get(...arguments); }, }; const proxy3 = new Proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world ``` The `Reflect` method still interacts with the object through object internal methods — it doesn't "de-proxify" the proxy if it's invoked on a proxy. If you use `Reflect` methods within a proxy trap, and the `Reflect` method call gets intercepted by the trap again, there may be infinite recursion. ### Terminology The following terms are used when talking about the functionality of proxies. - [handler](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy#handler_functions) - : The object passed as the second argument to the `Proxy` constructor. It contains the traps which define the behavior of the proxy. - trap - : The function that define the behavior for the corresponding [object internal method](#object_internal_methods). (This is analogous to the concept of _traps_ in operating systems.) - target - : Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target. - invariants - : Semantics that remain unchanged when implementing custom operations. If your trap implementation violates the invariants of a handler, a {{jsxref("TypeError")}} will be thrown. ### Object internal methods [Objects](/en-US/docs/Web/JavaScript/Data_structures#objects) are collections of properties. However, the language doesn't provide any machinery to _directly_ manipulate data stored in the object — rather, the object defines some internal methods specifying how it can be interacted with. For example, when you read `obj.x`, you may expect the following to happen: - The `x` property is searched up the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) until it is found. - If `x` is a data property, the property descriptor's `value` attribute is returned. - If `x` is an accessor property, the getter is invoked, and the return value of the getter is returned. There isn't anything special about this process in the language — it's just because ordinary objects, by default, have a `[[Get]]` internal method that is defined with this behavior. The `obj.x` property access syntax simply invokes the `[[Get]]` method on the object, and the object uses its own internal method implementation to determine what to return. As another example, [arrays](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) differ from normal objects, because they have a magic [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) property that, when modified, automatically allocates empty slots or removes elements from the array. Similarly, adding array elements automatically changes the `length` property. This is because arrays have a `[[DefineOwnProperty]]` internal method that knows to update `length` when an integer index is written to, or update the array contents when `length` is written to. Such objects whose internal methods have different implementations from ordinary objects are called _exotic objects_. `Proxy` enable developers to define their own exotic objects with full capacity. All objects have the following internal methods: | Internal method | Corresponding trap | | ----------------------- | -------------------------------------------------------------------------------- | | `[[GetPrototypeOf]]` | {{jsxref("Proxy/Proxy/getPrototypeOf", "getPrototypeOf()")}} | | `[[SetPrototypeOf]]` | {{jsxref("Proxy/Proxy/setPrototypeOf", "setPrototypeOf()")}} | | `[[IsExtensible]]` | {{jsxref("Proxy/Proxy/isExtensible", "isExtensible()")}} | | `[[PreventExtensions]]` | {{jsxref("Proxy/Proxy/preventExtensions", "preventExtensions()")}} | | `[[GetOwnProperty]]` | {{jsxref("Proxy/Proxy/getOwnPropertyDescriptor", "getOwnPropertyDescriptor()")}} | | `[[DefineOwnProperty]]` | {{jsxref("Proxy/Proxy/defineProperty", "defineProperty()")}} | | `[[HasProperty]]` | {{jsxref("Proxy/Proxy/has", "has()")}} | | `[[Get]]` | {{jsxref("Proxy/Proxy/get", "get()")}} | | `[[Set]]` | {{jsxref("Proxy/Proxy/set", "set()")}} | | `[[Delete]]` | {{jsxref("Proxy/Proxy/deleteProperty", "deleteProperty()")}} | | `[[OwnPropertyKeys]]` | {{jsxref("Proxy/Proxy/ownKeys", "ownKeys()")}} | Function objects also have the following internal methods: | Internal method | Corresponding trap | | --------------- | -------------------------------------------------- | | `[[Call]]` | {{jsxref("Proxy/Proxy/apply", "apply()")}} | | `[[Construct]]` | {{jsxref("Proxy/Proxy/construct", "construct()")}} | It's important to realize that all interactions with an object eventually boils down to the invocation of one of these internal methods, and that they are all customizable through proxies. This means almost no behavior (except certain critical invariants) is guaranteed in the language — everything is defined by the object itself. When you run [`delete obj.x`](/en-US/docs/Web/JavaScript/Reference/Operators/delete), there's no guarantee that [`"x" in obj`](/en-US/docs/Web/JavaScript/Reference/Operators/in) returns `false` afterwards — it depends on the object's implementations of `[[Delete]]` and `[[HasProperty]]`. A `delete obj.x` may log things to the console, modify some global state, or even define a new property instead of deleting the existing one, although these semantics should be avoided in your own code. All internal methods are called by the language itself, and are not directly accessible in JavaScript code. The {{jsxref("Reflect")}} namespace offers methods that do little more than call the internal methods, besides some input normalization/validation. In each trap's page, we list several typical situations when the trap is invoked, but these internal methods are called in _a lot_ of places. For example, array methods read and write to array through these internal methods, so methods like [`push()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) would also invoke `get()` and `set()` traps. Most of the internal methods are straightforward in what they do. The only two that may be confusable are `[[Set]]` and `[[DefineOwnProperty]]`. For normal objects, the former invokes setters; the latter doesn't. (And `[[Set]]` calls `[[DefineOwnProperty]]` internally if there's no existing property or the property is a data property.) While you may know that the `obj.x = 1` syntax uses `[[Set]]`, and {{jsxref("Object.defineProperty()")}} uses `[[DefineOwnProperty]]`, it's not immediately apparent what semantics other built-in methods and syntaxes use. For example, [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) use the `[[DefineOwnProperty]]` semantic, which is why setters defined in the superclass are not invoked when a field is declared on the derived class. ## Constructor - {{jsxref("Proxy/Proxy", "Proxy()")}} - : Creates a new `Proxy` object. > **Note:** There's no `Proxy.prototype` property, so `Proxy` instances do not have any special properties or methods. ## Static methods - {{jsxref("Proxy.revocable()")}} - : Creates a revocable `Proxy` object. ## Examples ### Basic example In this simple example, the number `37` gets returned as the default value when the property name is not in the object. It is using the {{jsxref("Proxy/Proxy/get", "get()")}} handler. ```js const handler = { get(obj, prop) { return prop in obj ? obj[prop] : 37; }, }; const p = new Proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log("c" in p, p.c); // false, 37 ``` ### No-op forwarding proxy In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it. ```js const target = {}; const p = new Proxy(target, {}); p.a = 37; // Operation forwarded to the target console.log(target.a); // 37 (The operation has been properly forwarded!) ``` Note that while this "no-op" works for plain JavaScript objects, it does not work for native objects, such as DOM elements, [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) objects, or anything that has internal slots. See [no private property forwarding](#no_private_property_forwarding) for more information. ### No private property forwarding A proxy is still another object with a different identity — it's a _proxy_ that operates between the wrapped object and the outside. As such, the proxy does not have direct access to the original object's [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties). ```js class Secret { #secret; constructor(secret) { this.#secret = secret; } get secret() { return this.#secret.replace(/\d+/, "[REDACTED]"); } } const aSecret = new Secret("123456"); console.log(aSecret.secret); // [REDACTED] // Looks like a no-op forwarding... const proxy = new Proxy(aSecret, {}); console.log(proxy.secret); // TypeError: Cannot read private member #secret from an object whose class did not declare it ``` This is because when the proxy's `get` trap is invoked, the `this` value is the `proxy` instead of the original `secret`, so `#secret` is not accessible. To fix this, use the original `secret` as `this`: ```js const proxy = new Proxy(aSecret, { get(target, prop, receiver) { // By default, it looks like Reflect.get(target, prop, receiver) // which has a different value of `this` return target[prop]; }, }); console.log(proxy.secret); ``` For methods, this means you have to redirect the method's `this` value to the original object as well: ```js class Secret { #x = 1; x() { return this.#x; } } const aSecret = new Secret(); const proxy = new Proxy(aSecret, { get(target, prop, receiver) { const value = target[prop]; if (value instanceof Function) { return function (...args) { return value.apply(this === receiver ? target : this, args); }; } return value; }, }); console.log(proxy.x()); ``` Some native JavaScript objects have properties called _[internal slots](https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-object-internal-methods-and-internal-slots)_, which are not accessible from JavaScript code. For example, [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) objects have an internal slot called `[[MapData]]`, which stores the key-value pairs of the map. As such, you cannot trivially create a forwarding proxy for a map: ```js const proxy = new Proxy(new Map(), {}); console.log(proxy.size); // TypeError: get size method called on incompatible Proxy ``` You have to use the "`this`-recovering" proxy illustrated above to work around this. ### Validation With a `Proxy`, you can easily validate the passed value for an object. This example uses the {{jsxref("Proxy/Proxy/set", "set()")}} handler. ```js const validator = { set(obj, prop, value) { if (prop === "age") { if (!Number.isInteger(value)) { throw new TypeError("The age is not an integer"); } if (value > 200) { throw new RangeError("The age seems invalid"); } } // The default behavior to store the value obj[prop] = value; // Indicate success return true; }, }; const person = new Proxy({}, validator); person.age = 100; console.log(person.age); // 100 person.age = "young"; // Throws an exception person.age = 300; // Throws an exception ``` ### Manipulating DOM nodes In this example we use `Proxy` to toggle an attribute of two different elements: so when we set the attribute on one element, the attribute is unset on the other one. We create a `view` object which is a proxy for an object with a `selected` property. The proxy handler defines the {{jsxref("Proxy/Proxy/set", "set()")}} handler. When we assign an HTML element to `view.selected`, the element's `'aria-selected'` attribute is set to `true`. If we then assign a different element to `view.selected`, this element's `'aria-selected'` attribute is set to `true` and the previous element's `'aria-selected'` attribute is automatically set to `false`. ```js const view = new Proxy( { selected: null, }, { set(obj, prop, newval) { const oldval = obj[prop]; if (prop === "selected") { if (oldval) { oldval.setAttribute("aria-selected", "false"); } if (newval) { newval.setAttribute("aria-selected", "true"); } } // The default behavior to store the value obj[prop] = newval; // Indicate success return true; }, }, ); const item1 = document.getElementById("item-1"); const item2 = document.getElementById("item-2"); // select item1: view.selected = item1; console.log(`item1: ${item1.getAttribute("aria-selected")}`); // item1: true // selecting item2 de-selects item1: view.selected = item2; console.log(`item1: ${item1.getAttribute("aria-selected")}`); // item1: false console.log(`item2: ${item2.getAttribute("aria-selected")}`); // item2: true ``` ### Value correction and an extra property The `products` proxy object evaluates the passed value and converts it to an array if needed. The object also supports an extra property called `latestBrowser` both as a getter and a setter. ```js const products = new Proxy( { browsers: ["Firefox", "Chrome"], }, { get(obj, prop) { // An extra property if (prop === "latestBrowser") { return obj.browsers[obj.browsers.length - 1]; } // The default behavior to return the value return obj[prop]; }, set(obj, prop, value) { // An extra property if (prop === "latestBrowser") { obj.browsers.push(value); return true; } // Convert the value if it is not an array if (typeof value === "string") { value = [value]; } // The default behavior to store the value obj[prop] = value; // Indicate success return true; }, }, ); console.log(products.browsers); // ['Firefox', 'Chrome'] products.browsers = "Safari"; // pass a string (by mistake) console.log(products.browsers); // ['Safari'] <- no problem, the value is an array products.latestBrowser = "Edge"; console.log(products.browsers); // ['Safari', 'Edge'] console.log(products.latestBrowser); // 'Edge' ``` ### A complete traps list example Now in order to create a complete sample `traps` list, for didactic purposes, we will try to proxify a _non-native_ object that is particularly suited to this type of operation: the `docCookies` global object created by [a simple cookie framework](https://reference.codeproject.com/dom/document/cookie/simple_document.cookie_framework). ```js /* const docCookies = ... get the "docCookies" object here: https://reference.codeproject.com/dom/document/cookie/simple_document.cookie_framework */ const docCookies = new Proxy(docCookies, { get(target, key) { return target[key] ?? target.getItem(key) ?? undefined; }, set(target, key, value) { if (key in target) { return false; } return target.setItem(key, value); }, deleteProperty(target, key) { if (!(key in target)) { return false; } return target.removeItem(key); }, ownKeys(target) { return target.keys(); }, has(target, key) { return key in target || target.hasItem(key); }, defineProperty(target, key, descriptor) { if (descriptor && "value" in descriptor) { target.setItem(key, descriptor.value); } return target; }, getOwnPropertyDescriptor(target, key) { const value = target.getItem(key); return value ? { value, writable: true, enumerable: true, configurable: false, } : undefined; }, }); /* Cookies test */ console.log((docCookies.myCookie1 = "First value")); console.log(docCookies.getItem("myCookie1")); docCookies.setItem("myCookie1", "Changed value"); console.log(docCookies.myCookie1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Proxies are awesome](https://youtu.be/sClk6aB_CPk) presentation by Brendan Eich at JSConf (2014)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/index.md
--- title: Proxy() constructor slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy page-type: javascript-constructor browser-compat: javascript.builtins.Proxy.Proxy --- {{JSRef}} The **`Proxy()`** constructor creates {{jsxref("Proxy")}} objects. ## Syntax ```js-nolint new Proxy(target, handler) ``` > **Note:** `Proxy()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions that define the behavior of the proxy when an operation is performed on it. ## Description Use the `Proxy()` constructor to create a new `Proxy` object. This constructor takes two mandatory arguments: - `target` is the object for which you want to create the proxy - `handler` is the object that defines the custom behavior of the proxy. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the `handler` object, you can customize specific aspects of the proxy's behavior. For example, by defining `get()` you can provide a customized version of the target's [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). ### Handler functions This section lists all the handler functions you can define. Handler functions are sometimes called _traps_, because they trap calls to the underlying target object. - {{jsxref("Proxy/Proxy/apply", "handler.apply()")}} - : A trap for a function call. - {{jsxref("Proxy/Proxy/construct", "handler.construct()")}} - : A trap for the {{jsxref("Operators/new", "new")}} operator. - {{jsxref("Proxy/Proxy/defineProperty", "handler.defineProperty()")}} - : A trap for {{jsxref("Object.defineProperty")}}. - {{jsxref("Proxy/Proxy/deleteProperty", "handler.deleteProperty()")}} - : A trap for the {{jsxref("Operators/delete", "delete")}} operator. - {{jsxref("Proxy/Proxy/get", "handler.get()")}} - : A trap for getting property values. - {{jsxref("Proxy/Proxy/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}} - : A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}. - {{jsxref("Proxy/Proxy/getPrototypeOf", "handler.getPrototypeOf()")}} - : A trap for {{jsxref("Object.getPrototypeOf")}}. - {{jsxref("Proxy/Proxy/has", "handler.has()")}} - : A trap for the {{jsxref("Operators/in", "in")}} operator. - {{jsxref("Proxy/Proxy/isExtensible", "handler.isExtensible()")}} - : A trap for {{jsxref("Object.isExtensible")}}. - {{jsxref("Proxy/Proxy/ownKeys", "handler.ownKeys()")}} - : A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}. - {{jsxref("Proxy/Proxy/preventExtensions", "handler.preventExtensions()")}} - : A trap for {{jsxref("Object.preventExtensions")}}. - {{jsxref("Proxy/Proxy/set", "handler.set()")}} - : A trap for setting property values. - {{jsxref("Proxy/Proxy/setPrototypeOf", "handler.setPrototypeOf()")}} - : A trap for {{jsxref("Object.setPrototypeOf")}}. ## Examples ### Selectively proxy property accessors In this example the target has two properties, `notProxied` and `proxied`. We define a handler that returns a different value for `proxied`, and lets any other accesses through to the target. ```js const target = { notProxied: "original value", proxied: "original value", }; const handler = { get(target, prop, receiver) { if (prop === "proxied") { return "replaced value"; } return Reflect.get(...arguments); }, }; const proxy = new Proxy(target, handler); console.log(proxy.notProxied); // "original value" console.log(proxy.proxied); // "replaced value" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Meta programming](/en-US/docs/Web/JavaScript/Guide/Meta_programming) guide - {{jsxref("Reflect")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/construct/index.md
--- title: handler.construct() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.construct --- {{JSRef}} The **`handler.construct()`** method is a trap for the `[[Construct]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as the {{jsxref("Operators/new", "new")}} operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself be a valid constructor. {{EmbedInteractiveExample("pages/js/proxyhandler-construct.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { construct(target, argumentsList, newTarget) { } }); ``` ### Parameters The following parameters are passed to the `construct()` method. `this` is bound to the handler. - `target` - : The target object. - `argumentsList` - : The list of arguments for the constructor. - `newTarget` - : The constructor that was originally called. ### Return value The `construct` method must return an object. ## Description ### Interceptions This trap can intercept these operations: - The [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator: `new myFunction(...args)` - {{jsxref("Reflect.construct()")}} Or any other operation that invokes the `[[Construct]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - The result must be an `Object`. ## Examples ### Trapping the new operator The following code traps the {{jsxref("Operators/new", "new")}} operator. ```js const p = new Proxy(function () {}, { construct(target, argumentsList, newTarget) { console.log(`called: ${argumentsList}`); return { value: argumentsList[0] * 10 }; }, }); console.log(new p(1).value); // "called: 1" // 10 ``` The following code violates the invariant. ```js example-bad const p = new Proxy(function () {}, { construct(target, argumentsList, newTarget) { return 1; }, }); new p(); // TypeError is thrown ``` The following code improperly initializes the proxy. The `target` in Proxy initialization must itself be a valid constructor for the {{jsxref("Operators/new", "new")}} operator. ```js example-bad const p = new Proxy( {}, { construct(target, argumentsList, newTarget) { return {}; }, }, ); new p(); // TypeError is thrown, "p" is not a constructor ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Operators/new", "new")}} - {{jsxref("Reflect.construct()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/get/index.md
--- title: handler.get() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/get page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.get --- {{JSRef}} The **`handler.get()`** method is a trap for the `[[Get]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). {{EmbedInteractiveExample("pages/js/proxyhandler-get.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { get(target, property, receiver) { } }); ``` ### Parameters The following parameters are passed to the `get()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or {{jsxref("Symbol")}} of the property to get. - `receiver` - : Either the proxy or an object that inherits from the proxy. ### Return value The `get()` method can return any value. ## Description ### Interceptions This trap can intercept these operations: - Property access: `proxy[foo]` and `proxy.bar` - {{jsxref("Reflect.get()")}} Or any other operation that invokes the `[[Get]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. - The value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has `undefined` as its `[[Get]]` attribute. ## Examples ### Trap for getting a property value The following code traps getting a property value. ```js const p = new Proxy( {}, { get(target, property, receiver) { console.log(`called: ${property}`); return 10; }, }, ); console.log(p.a); // "called: a" // 10 ``` The following code violates an invariant. ```js const obj = {}; Object.defineProperty(obj, "a", { configurable: false, enumerable: false, value: 10, writable: false, }); const p = new Proxy(obj, { get(target, property) { return 20; }, }); p.a; // TypeError is thrown ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Reflect.get()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.md
--- title: handler.setPrototypeOf() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.setPrototypeOf --- {{JSRef}} The **`handler.setPrototypeOf()`** method is a trap for the `[[SetPrototypeOf]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.setPrototypeOf()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-setprototypeof.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { setPrototypeOf(target, prototype) { } }); ``` ### Parameters The following parameters are passed to the `setPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. - `prototype` - : The object's new prototype or `null`. ### Return value The `setPrototypeOf()` method returns `true` if the `[[Prototype]]` was successfully changed, otherwise `false`. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.setPrototypeOf()")}} - {{jsxref("Reflect.setPrototypeOf()")}} Or any other operation that invokes the `[[SetPrototypeOf]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - If `target` is not extensible, the `prototype` parameter must be the same value as `Object.getPrototypeOf(target)`. ## Examples If you want to disallow setting a new prototype for your object, your handler's `setPrototypeOf()` method can either return `false`, or it can throw an exception. ### Approach 1: Returning false This approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. For example, {{jsxref("Object.setPrototypeOf()")}} will create and throw a {{jsxref("TypeError")}} itself. If the mutation is performed by an operation that _doesn't_ ordinarily throw in case of failure, such as {{jsxref("Reflect.setPrototypeOf()")}}, no exception will be thrown. ```js const handlerReturnsFalse = { setPrototypeOf(target, newProto) { return false; }, }; const newProto = {}, target = {}; const p1 = new Proxy(target, handlerReturnsFalse); Object.setPrototypeOf(p1, newProto); // throws a TypeError Reflect.setPrototypeOf(p1, newProto); // returns false ``` ### Approach 2: Throwing an Exception The latter approach will cause _any_ operation that attempts to mutate, to throw. This approach is best if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value. ```js const handlerThrows = { setPrototypeOf(target, newProto) { throw new Error("custom error"); }, }; const newProto = {}, target = {}; const p2 = new Proxy(target, handlerThrows); Object.setPrototypeOf(p2, newProto); // throws new Error("custom error") Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error") ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.setPrototypeOf()")}} - {{jsxref("Reflect.setPrototypeOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/has/index.md
--- title: handler.has() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/has page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.has --- {{JSRef}} The **`handler.has()`** method is a trap for the `[[HasProperty]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as the {{jsxref("Operators/in", "in")}} operator. {{EmbedInteractiveExample("pages/js/proxyhandler-has.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { has(target, prop) { } }); ``` ### Parameters The following parameters are passed to `has()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name or {{jsxref("Symbol")}} of the property to check for existence. ### Return value The `has()` method must return a boolean value. ## Description ### Interceptions This trap can intercept these operations: - The [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) operator: `foo in proxy` - [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) check: `with(proxy) { (foo); }` - {{jsxref("Reflect.has()")}} Or any other operation that invokes the `[[HasProperty]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ## Examples ### Trapping the in operator The following code traps the {{jsxref("Operators/in", "in")}} operator. ```js const p = new Proxy( {}, { has(target, prop) { console.log(`called: ${prop}`); return true; }, }, ); console.log("a" in p); // "called: a" // true ``` The following code violates an invariant. ```js example-bad const obj = { a: 10 }; Object.preventExtensions(obj); const p = new Proxy(obj, { has(target, prop) { return false; }, }); "a" in p; // TypeError is thrown ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Operators/in", "in")}} - {{jsxref("Reflect.has()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/set/index.md
--- title: handler.set() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.set --- {{JSRef}} The **`handler.set()`** method is a trap for the `[[Set]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as using [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) to set a property's value. {{EmbedInteractiveExample("pages/js/proxyhandler-set.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { set(target, property, value, receiver) { } }); ``` ### Parameters The following parameters are passed to the `set()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or {{jsxref("Symbol")}} of the property to set. - `value` - : The new value of the property to set. - `receiver` - : The object to which the assignment was originally directed. This is usually the proxy itself. But a `set()` handler can also be called indirectly, via the prototype chain or various other ways. For example, suppose a script does `obj.name = "jen"`, and `obj` is not a proxy, and has no own property `.name`, but it has a proxy on its prototype chain. That proxy's `set()` handler will be called, and `obj` will be passed as the receiver. ### Return value The `set()` method should return a boolean value. - Return `true` to indicate that assignment succeeded. - If the `set()` method returns `false`, and the assignment happened in strict-mode code, a {{jsxref("TypeError")}} will be thrown. ## Description ### Interceptions This trap can intercept these operations: - Property assignment: `proxy[foo] = bar` and `proxy.foo = bar` - {{jsxref("Reflect.set()")}} Or any other operation that invokes the `[[Set]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. - Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has `undefined` as its `[[Set]]` attribute. - In strict mode, a `false` return value from the `set()` handler will throw a {{jsxref("TypeError")}} exception. ## Examples ### Trap setting of a property value The following code traps setting a property value. ```js const p = new Proxy( {}, { set(target, prop, value, receiver) { target[prop] = value; console.log(`property set: ${prop} = ${value}`); return true; }, }, ); console.log("a" in p); // false p.a = 10; // "property set: a = 10" console.log("a" in p); // true console.log(p.a); // 10 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Reflect.set()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/getownpropertydescriptor/index.md
--- title: handler.getOwnPropertyDescriptor() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.getOwnPropertyDescriptor --- {{JSRef}} The **`handler.getOwnPropertyDescriptor()`** method is a trap for the `[[GetOwnProperty]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.getOwnPropertyDescriptor()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-getownpropertydescriptor.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { getOwnPropertyDescriptor(target, prop) { } }); ``` ### Parameters The following parameters are passed to the `getOwnPropertyDescriptor()` method. `this` is bound to the handler. - `target` - : The target object. - `prop` - : The name of the property whose description should be retrieved. ### Return value The `getOwnPropertyDescriptor()` method must return an object or `undefined`. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.getOwnPropertyDescriptor()")}} - {{jsxref("Reflect.getOwnPropertyDescriptor()")}} Or any other operation that invokes the `[[GetOwnProperty]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - `getOwnPropertyDescriptor()` must return an object or `undefined`. - A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. - A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible. - A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. - The result of `Object.getOwnPropertyDescriptor(target)` can be applied to the target object using `Object.defineProperty()` and will not throw an exception. ## Examples ### Trapping of getOwnPropertyDescriptor The following code traps {{jsxref("Object.getOwnPropertyDescriptor()")}}. ```js const p = new Proxy( { a: 20 }, { getOwnPropertyDescriptor(target, prop) { console.log(`called: ${prop}`); return { configurable: true, enumerable: true, value: 10 }; }, }, ); console.log(Object.getOwnPropertyDescriptor(p, "a").value); // "called: a" // 10 ``` The following code violates an invariant. ```js example-bad const obj = { a: 10 }; Object.preventExtensions(obj); const p = new Proxy(obj, { getOwnPropertyDescriptor(target, prop) { return undefined; }, }); Object.getOwnPropertyDescriptor(p, "a"); // TypeError is thrown ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.getOwnPropertyDescriptor()")}} - {{jsxref("Reflect.getOwnPropertyDescriptor()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/getprototypeof/index.md
--- title: handler.getPrototypeOf() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getPrototypeOf page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.getPrototypeOf --- {{JSRef}} The **`handler.getPrototypeOf()`** method is a trap for the `[[GetPrototypeOf]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.getPrototypeOf()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-getprototypeof.html", "taller")}} ## Syntax ```js-nolint new Proxy(obj, { getPrototypeOf(target) { // … } }); ``` ### Parameters The following parameter is passed to the `getPrototypeOf()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `getPrototypeOf()` method must return an object or `null`. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.getPrototypeOf()")}} - {{jsxref("Reflect.getPrototypeOf()")}} - [`__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) - {{jsxref("Object.prototype.isPrototypeOf()")}} - {{jsxref("Operators/instanceof", "instanceof")}} Or any other operation that invokes the `[[GetPrototypeOf]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - `getPrototypeOf()` method must return an object or `null`. - If `target` is not extensible, `Object.getPrototypeOf(proxy)` method must return the same value as `Object.getPrototypeOf(target)`. ## Examples ### Basic usage ```js const obj = {}; const proto = {}; const handler = { getPrototypeOf(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; }, }; const p = new Proxy(obj, handler); console.log(Object.getPrototypeOf(p) === proto); // true ``` ### Five ways to trigger the getPrototypeOf trap ```js const obj = {}; const p = new Proxy(obj, { getPrototypeOf(target) { return Array.prototype; }, }); console.log( Object.getPrototypeOf(p) === Array.prototype, // true Reflect.getPrototypeOf(p) === Array.prototype, // true p.__proto__ === Array.prototype, // true Array.prototype.isPrototypeOf(p), // true p instanceof Array, // true ); ``` ### Two kinds of exceptions ```js example-bad const obj = {}; const p = new Proxy(obj, { getPrototypeOf(target) { return "foo"; }, }); Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null const obj2 = Object.preventExtensions({}); const p2 = new Proxy(obj2, { getPrototypeOf(target) { return {}; }, }); Object.getPrototypeOf(p2); // TypeError: expected same prototype value ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.getPrototypeOf()")}} - {{jsxref("Reflect.getPrototypeOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.md
--- title: handler.ownKeys() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.ownKeys --- {{JSRef}} The **`handler.ownKeys()`** method is a trap for the `[[OwnPropertyKeys]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.keys()")}}, {{jsxref("Reflect.ownKeys()")}}, etc. {{EmbedInteractiveExample("pages/js/proxyhandler-ownkeys.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { ownKeys(target) { } }); ``` ### Parameters The following parameter is passed to the `ownKeys()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `ownKeys()` method must return an enumerable object. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.getOwnPropertyNames()")}} - {{jsxref("Object.getOwnPropertySymbols()")}} - {{jsxref("Object.keys()")}} - {{jsxref("Reflect.ownKeys()")}} Or any other operation that invokes the `[[OwnPropertyKeys]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - The result of `ownKeys()` must be an array. - The type of each array element is either a {{jsxref("String")}} or a {{jsxref("Symbol")}}. - The result List must contain the keys of all non-configurable own properties of the target object. - If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values. ## Examples ### Trapping of getOwnPropertyNames The following code traps {{jsxref("Object.getOwnPropertyNames()")}}. ```js const p = new Proxy( {}, { ownKeys(target) { console.log("called"); return ["a", "b", "c"]; }, }, ); console.log(Object.getOwnPropertyNames(p)); // "called" // [ 'a', 'b', 'c' ] ``` The following code violates an invariant. ```js example-bad const obj = {}; Object.defineProperty(obj, "a", { configurable: false, enumerable: true, value: 10, }); const p = new Proxy(obj, { ownKeys(target) { return [123, 12.5, true, false, undefined, null, {}, []]; }, }); console.log(Object.getOwnPropertyNames(p)); // TypeError: proxy [[OwnPropertyKeys]] must return an array // with only string and symbol elements ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.getOwnPropertyNames()")}} - {{jsxref("Reflect.ownKeys()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/deleteproperty/index.md
--- title: handler.deleteProperty() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.deleteProperty --- {{JSRef}} The **`handler.deleteProperty()`** method is a trap for the `[[Delete]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as the {{jsxref("Operators/delete", "delete")}} operator. {{EmbedInteractiveExample("pages/js/proxyhandler-deleteproperty.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { deleteProperty(target, property) { } }); ``` ### Parameters The following parameters are passed to the `deleteProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or {{jsxref("Symbol")}} of the property to delete. ### Return value The `deleteProperty()` method must return a boolean value indicating whether or not the property has been successfully deleted. ## Description ### Interceptions This trap can intercept these operations: - The [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator: `delete proxy[foo]` and `delete proxy.foo` - {{jsxref("Reflect.deleteProperty()")}} Or any other operation that invokes the `[[Delete]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - A property cannot be deleted, if it exists as a non-configurable own property of the target object. ## Examples ### Trapping the delete operator The following code traps the {{jsxref("Operators/delete", "delete")}} operator. ```js const p = new Proxy( {}, { deleteProperty(target, prop) { if (!(prop in target)) { console.log(`property not found: ${prop}`); return false; } delete target[prop]; console.log(`property removed: ${prop}`); return true; }, }, ); p.a = 10; console.log("a" in p); // true const result1 = delete p.a; // "property removed: a" console.log(result1); // true console.log("a" in p); // false const result2 = delete p.a; // "property not found: a" console.log(result2); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Operators/delete", "delete")}} - {{jsxref("Reflect.deleteProperty()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/isextensible/index.md
--- title: handler.isExtensible() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/isExtensible page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.isExtensible --- {{JSRef}} The **`handler.isExtensible()`** method is a trap for the `[[IsExtensible]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.isExtensible()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-isextensible.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { isExtensible(target) { } }); ``` ### Parameters The following parameter is passed to the `isExtensible()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `isExtensible()` method must return a boolean value. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.isExtensible()")}} - {{jsxref("Reflect.isExtensible()")}} Or any other operation that invokes the `[[IsExtensible]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - `Object.isExtensible(proxy)` must return the same value as `Object.isExtensible(target)`. ## Examples ### Trapping of isExtensible The following code traps {{jsxref("Object.isExtensible()")}}. ```js const p = new Proxy( {}, { isExtensible(target) { console.log("called"); return true; }, }, ); console.log(Object.isExtensible(p)); // "called" // true ``` The following code violates the invariant. ```js example-bad const p = new Proxy( {}, { isExtensible(target) { return false; }, }, ); Object.isExtensible(p); // TypeError is thrown ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.isExtensible()")}} - {{jsxref("Reflect.isExtensible()")}} - {{jsxref("Reflect.preventExtensions()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/apply/index.md
--- title: handler.apply() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.apply --- {{JSRef}} The **`handler.apply()`** method is a trap for the `[[Call]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as function calls. {{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { apply(target, thisArg, argumentsList) { } }); ``` ### Parameters The following parameters are passed to the `apply()` method. `this` is bound to the handler. - `target` - : The target callable object. - `thisArg` - : The `this` argument for the call. - `argumentsList` - : The list of arguments for the call. ### Return value The `apply()` method can return any value. ## Description ### Interceptions This trap can intercept these operations: - Function call: `proxy(...args)` - {{jsxref("Function.prototype.apply()")}} and {{jsxref("Function.prototype.call()")}} - {{jsxref("Reflect.apply()")}} Or any other operation that invokes the `[[Call]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - The `target` must be a callable itself. That is, it must be a function object. ## Examples ### Trapping a function call The following code traps a function call. ```js const p = new Proxy(function () {}, { apply(target, thisArg, argumentsList) { console.log(`called: ${argumentsList}`); return argumentsList[0] + argumentsList[1] + argumentsList[2]; }, }); console.log(p(1, 2, 3)); // "called: 1,2,3" // 6 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Function.prototype.apply()")}} - {{jsxref("Function.prototype.call()")}} - {{jsxref("Reflect.apply()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.md
--- title: handler.preventExtensions() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/preventExtensions page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.preventExtensions --- {{JSRef}} The **`handler.preventExtensions()`** method is a trap for the `[[PreventExtensions]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.preventExtensions()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-preventextensions.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { preventExtensions(target) { } }); ``` ### Parameters The following parameter is passed to the `preventExtensions()` method. `this` is bound to the handler. - `target` - : The target object. ### Return value The `preventExtensions()` method must return a boolean value. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.preventExtensions()")}} - {{jsxref("Reflect.preventExtensions()")}} - {{jsxref("Object.seal()")}} - {{jsxref("Object.freeze()")}} Or any other operation that invokes the `[[PreventExtensions]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - `Object.preventExtensions(proxy)` only returns `true` if `Object.isExtensible(proxy)` is `false`. ## Examples ### Trapping of preventExtensions The following code traps {{jsxref("Object.preventExtensions()")}}. ```js const p = new Proxy( {}, { preventExtensions(target) { console.log("called"); Object.preventExtensions(target); return true; }, }, ); console.log(Object.preventExtensions(p)); // "called" // false ``` The following code violates the invariant. ```js example-bad const p = new Proxy( {}, { preventExtensions(target) { return true; }, }, ); Object.preventExtensions(p); // TypeError is thrown ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.preventExtensions()")}} - {{jsxref("Reflect.preventExtensions()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/proxy/defineproperty/index.md
--- title: handler.defineProperty() slug: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty page-type: javascript-instance-method browser-compat: javascript.builtins.Proxy.handler.defineProperty --- {{JSRef}} The **`handler.defineProperty()`** method is a trap for the `[[DefineOwnProperty]]` [object internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods), which is used by operations such as {{jsxref("Object.defineProperty()")}}. {{EmbedInteractiveExample("pages/js/proxyhandler-defineproperty.html", "taller")}} ## Syntax ```js-nolint new Proxy(target, { defineProperty(target, property, descriptor) { } }); ``` ### Parameters The following parameters are passed to the `defineProperty()` method. `this` is bound to the handler. - `target` - : The target object. - `property` - : The name or {{jsxref("Symbol")}} of the property whose description is to be retrieved. - `descriptor` - : The descriptor for the property being defined or modified. ### Return value The `defineProperty()` method must return a {{jsxref("Boolean")}} indicating whether or not the property has been successfully defined. ## Description ### Interceptions This trap can intercept these operations: - {{jsxref("Object.defineProperty()")}}, {{jsxref("Object.defineProperties()")}} - {{jsxref("Reflect.defineProperty()")}} Or any other operation that invokes the `[[DefineOwnProperty]]` [internal method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#object_internal_methods). ### Invariants If the following invariants are violated, the trap throws a {{jsxref("TypeError")}} when invoked. - A property cannot be added, if the target object is not extensible. - A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. - A property may not be non-configurable, if a corresponding configurable property of the target object exists. - If a property has a corresponding target object property then `Object.defineProperty(target, prop, descriptor)` will not throw an exception. - In strict mode, a `false` return value from the `defineProperty()` handler will throw a {{jsxref("TypeError")}} exception. ## Examples ### Trapping of defineProperty The following code traps {{jsxref("Object.defineProperty()")}}. ```js const p = new Proxy( {}, { defineProperty(target, prop, descriptor) { console.log(`called: ${prop}`); return true; }, }, ); const desc = { configurable: true, enumerable: true, value: 10 }; Object.defineProperty(p, "a", desc); // "called: a" ``` When calling {{jsxref("Object.defineProperty()")}} or {{jsxref("Reflect.defineProperty()")}}, the `descriptor` passed to `defineProperty()` trap has one restriction—only following properties are usable (non-standard properties will be ignored): - `enumerable` - `configurable` - `writable` - `value` - `get` - `set` ```js const p = new Proxy( {}, { defineProperty(target, prop, descriptor) { console.log(descriptor); return Reflect.defineProperty(target, prop, descriptor); }, }, ); Object.defineProperty(p, "name", { value: "proxy", type: "custom", }); // { value: 'proxy' } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}} - [`Proxy()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) - {{jsxref("Object.defineProperty()")}} - {{jsxref("Reflect.defineProperty()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy
data/mdn-content/files/en-us/web/javascript/reference/global_objects/proxy/revocable/index.md
--- title: Proxy.revocable() slug: Web/JavaScript/Reference/Global_Objects/Proxy/revocable page-type: javascript-static-method browser-compat: javascript.builtins.Proxy.revocable --- {{JSRef}} The **`Proxy.revocable()`** static method creates a revocable {{jsxref("Proxy")}} object. ## Syntax ```js-nolint Proxy.revocable(target, handler) ``` ### Parameters - `target` - : A target object to wrap with `Proxy`. It can be any sort of object, including a native array, a function, or even another proxy. - `handler` - : An object whose properties are functions defining the behavior of `proxy` when an operation is performed on it. ### Return value A plain object with the following two properties: - `proxy` - : A Proxy object exactly the same as one created with a [`new Proxy(target, handler)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) call. - `revoke` - : A function with no parameters to revoke (switch off) the `proxy`. ## Description The `Proxy.revocable()` factory function is the same as the [`Proxy()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) constructor, except that in addition to creating a proxy object, it also creates a `revoke` function that can be called to disable the proxy. The proxy object and the `revoke` function are wrapped in a plain object. The `revoke` function does not take any parameters, nor does it rely on the `this` value. The created `proxy` object is attached to the `revoke` function as a [private property](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) that the `revoke` function accesses on itself when called (the existence of the private property is not observable from the outside, but it has implications on how garbage collection happens). The `proxy` object is _not_ captured within the [closure](/en-US/docs/Web/JavaScript/Closures) of the `revoke` function (which will make garbage collection of `proxy` impossible if `revoke` is still alive). After the `revoke()` function gets called, the proxy becomes unusable: any trap to a handler throws a {{jsxref("TypeError")}}. Once a proxy is revoked, it remains revoked, and calling `revoke()` again has no effect — in fact, the call to `revoke()` detaches the `proxy` object from the `revoke` function, so the `revoke` function will not be able to access the proxy again at all. If the proxy is not referenced elsewhere, it will then be eligible for garbage collection. The `revoke` function also detaches `target` and `handler` from the `proxy`, so if `target` is not referenced elsewhere, it will also be eligible for garbage collection, even when its proxy is still alive, since there's no longer a way to meaningfully interact with the target object. Letting users interact with an object through a revocable proxy allows you to [control the lifetime](/en-US/docs/Web/JavaScript/Memory_management) of the object exposed to the user — you can make the object garbage-collectable even when the user is still holding a reference to its proxy. ## Examples ### Using Proxy.revocable() ```js const revocable = Proxy.revocable( {}, { get(target, name) { return `[[${name}]]`; }, }, ); const proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // TypeError is thrown proxy.foo = 1; // TypeError again delete proxy.foo; // still TypeError typeof proxy; // "object", typeof doesn't trigger any trap ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Proxy")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/isnan/index.md
--- title: isNaN() slug: Web/JavaScript/Reference/Global_Objects/isNaN page-type: javascript-function browser-compat: javascript.builtins.isNaN --- {{jsSidebar("Objects")}} The **`isNaN()`** function determines whether a value is {{jsxref("NaN")}}, first converting the value to a number if necessary. Because coercion inside the `isNaN()` function can be [surprising](#description), you may prefer to use {{jsxref("Number.isNaN()")}}. {{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}} ## Syntax ```js-nolint isNaN(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `true` if the given value is {{jsxref("NaN")}} after being [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `false`. ## Description `isNaN()` is a function property of the global object. For number values, `isNaN()` tests if the number is the value [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN). When the argument to the `isNaN()` function is not of type [Number](/en-US/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against {{jsxref("NaN")}}. This behavior of `isNaN()` for non-numeric arguments can be confusing! For example, an empty string is coerced to 0, while a boolean is coerced to 0 or 1; both values are intuitively "not numbers", but they don't evaluate to `NaN`, so `isNaN()` returns `false`. Therefore, `isNaN()` answers neither the question "is the input the floating point {{jsxref("NaN")}} value" nor the question "is the input not a number". {{jsxref("Number.isNaN()")}} is a more reliable way to test whether a value is the number value `NaN` or not. Alternatively, the expression `x !== x` can be used, and neither of the solutions is subject to the false positives that make the global `isNaN()` unreliable. To test if a value is a number, use [`typeof x === "number"`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof). The `isNaN()` function answers the question "is the input functionally equivalent to {{jsxref("NaN")}} when used in a number context". If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression as if it's a valid number that's not `NaN`. If `isNaN(x)` returns `true`, `x` will get coerced to `NaN` and make most arithmetic expressions return `NaN` (because `NaN` propagates). You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), and handle values that are not number-like by throwing an error, providing a default value, etc. This way, you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. > **Note:** The [`+` operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) performs both number addition and string concatenation. Therefore, even if `isNaN()` returns `false` for both operands, the `+` operator may still return a string, because it's not used as an arithmetic operator. For example, `isNaN("1")` returns `false`, but `"1" + 1` returns `"11"`. To be sure that you are working with numbers, [coerce the value to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) and use {{jsxref("Number.isNaN()")}} to test the result. ## Examples Note how `isNaN()` returns `true` for values that are not the value `NaN` but are not numbers either: ```js isNaN(NaN); // true isNaN(undefined); // true isNaN({}); // true isNaN(true); // false isNaN(null); // false isNaN(37); // false // Strings isNaN("37"); // false: "37" is converted to the number 37 which is not NaN isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN isNaN("37,5"); // true isNaN("123ABC"); // true: Number("123ABC") is NaN isNaN(""); // false: the empty string is converted to 0 which is not NaN isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN // Dates isNaN(new Date()); // false; Date objects can be converted to a number (timestamp) isNaN(new Date().toString()); // true; the string representation of a Date object cannot be parsed as a number // Arrays isNaN([]); // false; the primitive representation is "", which coverts to the number 0 isNaN([1]); // false; the primitive representation is "1" isNaN([1, 2]); // true; the primitive representation is "1,2", which cannot be parsed as number ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("NaN")}} - {{jsxref("Number.isNaN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/index.md
--- title: Function slug: Web/JavaScript/Reference/Global_Objects/Function page-type: javascript-class browser-compat: javascript.builtins.Function --- {{JSRef}} The **`Function`** object provides methods for [functions](/en-US/docs/Web/JavaScript/Reference/Functions). In JavaScript, every function is actually a `Function` object. ## Constructor - {{jsxref("Function/Function", "Function()")}} - : Creates a new `Function` object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to {{jsxref("Global_Objects/eval", "eval()")}}. However, unlike `eval()`, the `Function` constructor creates functions that execute in the global scope only. ## Instance properties These properties are defined on `Function.prototype` and shared by all `Function` instances. - {{jsxref("Function.prototype.arguments")}} {{deprecated_inline}} {{non-standard_inline}} - : Represents the arguments passed to this function. For [strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode), arrow, async, and generator functions, accessing the `arguments` property throws a {{jsxref("TypeError")}}. Use the {{jsxref("Functions/arguments", "arguments")}} object inside function closures instead. - {{jsxref("Function.prototype.caller")}} {{deprecated_inline}} {{non-standard_inline}} - : Represents the function that invoked this function. For [strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode), arrow, async, and generator functions, accessing the `caller` property throws a {{jsxref("TypeError")}}. - {{jsxref("Object/constructor", "Function.prototype.constructor")}} - : The constructor function that created the instance object. For `Function` instances, the initial value is the {{jsxref("Function/Function", "Function")}} constructor. These properties are own properties of each `Function` instance. - {{jsxref("Function/displayName", "displayName")}} {{non-standard_inline}} {{optional_inline}} - : The display name of the function. - {{jsxref("Function/length", "length")}} - : Specifies the number of arguments expected by the function. - {{jsxref("Function/name", "name")}} - : The name of the function. - {{jsxref("Function/prototype", "prototype")}} - : Used when the function is used as a constructor with the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator. It will become the new object's prototype. ## Instance methods - {{jsxref("Function.prototype.apply()")}} - : Calls a function with a given `this` value and optional arguments provided as an array (or an [array-like object](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). - {{jsxref("Function.prototype.bind()")}} - : Creates a new function that, when called, has its `this` keyword set to a provided value, optionally with a given sequence of arguments preceding any provided when the new function is called. - {{jsxref("Function.prototype.call()")}} - : Calls a function with a given `this` value and optional arguments. - {{jsxref("Function.prototype.toString()")}} - : Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toString")}} method. - [`Function.prototype[@@hasInstance]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance) - : Specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. Called by the [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator. ## Examples ### Difference between Function constructor and function declaration 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 created. This is different from using {{jsxref("Global_Objects/eval", "eval()")}} with code for a function expression. ```js // Create a global property with `var` var x = 10; function createFunction1() { const x = 20; return new Function("return x;"); // this `x` refers to global `x` } function createFunction2() { const x = 20; function f() { return x; // this `x` refers to the local `x` above } return f; } const f1 = createFunction1(); console.log(f1()); // 10 const f2 = createFunction2(); console.log(f2()); // 20 ``` While this code works in web browsers, `f1()` will produce a `ReferenceError` in Node.js, as `x` will not be found. This is because the top-level scope in Node is not the global scope, and `x` will be local to the module. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function) - [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) - {{jsxref("AsyncFunction")}} - {{jsxref("AsyncGeneratorFunction")}} - {{jsxref("GeneratorFunction")}} - {{jsxref("Functions", "Functions", "", 1)}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/caller/index.md
--- title: Function.prototype.caller slug: Web/JavaScript/Reference/Global_Objects/Function/caller page-type: javascript-instance-accessor-property status: - deprecated - non-standard browser-compat: javascript.builtins.Function.caller --- {{JSRef}}{{Non-standard_Header}}{{Deprecated_Header}} > **Note:** In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), accessing `caller` of a function throws an error — the API is removed with no replacement. This is to prevent code from being able to "walk the stack", which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read [the rationale for the deprecation of `arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee#description). The **`caller`** accessor property of {{jsxref("Function")}} instances returns the function that invoked this function. For [strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode), arrow, async, and generator functions, accessing the `caller` property throws a {{jsxref("TypeError")}}. ## Description If the function `f` was invoked by the top-level code, the value of `f.caller` is {{jsxref("Operators/null", "null")}}; otherwise it's the function that called `f`. If the function that called `f` is a strict mode function, the value of `f.caller` is also `null`. Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `caller` accessor that unconditionally throws a {{jsxref("TypeError")}} for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the `caller` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.caller` accessor to specially handle `this` values that are non-strict functions. ```js (function f() { if (Object.hasOwn(f, "caller")) { console.log( "caller is an own property with descriptor", Object.getOwnPropertyDescriptor(f, "caller"), ); } else { console.log( "f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller", ); console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(f), "caller", ).get.call(f), ); } })(); // In Chrome: // caller is an own property with descriptor {value: null, writable: false, enumerable: false, configurable: false} // In Firefox: // f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller // null ``` This property replaces the obsolete `arguments.caller` property of the {{jsxref("Functions/arguments", "arguments")}} object. The special property `__caller__`, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons. ## Examples ### Checking the value of a function's caller property The following code checks the value a function's `caller` property. ```js function myFunc() { if (myFunc.caller === null) { return "The function was called from the top!"; } else { return `This function's caller was ${myFunc.caller}`; } } ``` ### Reconstructing the stack and recursion Note that in case of recursion, you can't reconstruct the call stack using this property. Consider: ```js function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); ``` At the moment `stop()` is called the call stack will be: ```plain f(2) -> g(1) -> f(1) -> g(0) -> stop() ``` The following is true: ```js stop.caller === g && f.caller === g && g.caller === f; ``` so if you tried to get the stack trace in the `stop()` function like this: ```js let f = stop; let stack = "Stack trace:"; while (f) { stack += `\n${f.name}`; f = f.caller; } ``` the loop would never stop. ### Strict mode caller If the caller is a strict mode function, the value of `caller` is `null`. ```js function callerFunc() { calleeFunc(); } function strictCallerFunc() { "use strict"; calleeFunc(); } function calleeFunc() { console.log(calleeFunc.caller); } (function () { callerFunc(); })(); // Logs [Function: callerFunc] (function () { strictCallerFunc(); })(); // Logs null ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Function.prototype.name")}} - {{jsxref("Functions/arguments", "arguments")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/name/index.md
--- title: "Function: name" slug: Web/JavaScript/Reference/Global_Objects/Function/name page-type: javascript-instance-data-property browser-compat: javascript.builtins.Function.name --- {{JSRef}} The **`name`** data property of a {{jsxref("Function")}} instance indicates the function's name as specified when it was created, or it may be either `anonymous` or `''` (an empty string) for functions created anonymously. {{EmbedInteractiveExample("pages/js/function-name.html")}} ## Value A string. {{js_property_attributes(0, 0, 1)}} > **Note:** In non-standard, pre-ES2015 implementations the `configurable` attribute was `false` as well. ## Description The function's `name` property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. The `name` property is read-only and cannot be changed by the assignment operator: ```js function someFunction() {} someFunction.name = "otherFunction"; console.log(someFunction.name); // someFunction ``` To change it, use {{jsxref("Object.defineProperty()")}}. The `name` property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred. ### Function declaration The `name` property returns the name of a function declaration. ```js function doSomething() {} doSomething.name; // "doSomething" ``` ### Default-exported function declaration An [`export default`](/en-US/docs/Web/JavaScript/Reference/Statements/export) declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is `"default"`. ```js // -- someModule.js -- export default function () {} // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default" ``` ### Function constructor Functions created with the [`Function()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) constructor have name "anonymous". ```js new Function().name; // "anonymous" ``` ### Function expression If the function expression is named, that name is used as the `name` property. ```js const someFunction = function someFunctionName() {}; someFunction.name; // "someFunctionName" ``` Anonymous function expressions created using the keyword `function` or arrow functions would have `""` (an empty string) as their name. ```js (function () {}).name; // "" (() => {}).name; // "" ``` However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate. One practical case where the name cannot be inferred is a function returned from another function: ```js function getFoo() { return () => {}; } getFoo().name; // "" ``` ### Variable declaration and method Variables and methods can infer the name of an anonymous function from its syntactic position. ```js const f = function () {}; const object = { someMethod: function () {}, }; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod" ``` The same applies to assignment: ```js let f; f = () => {}; f.name; // "f" ``` ### Initializer and default value Functions in initializers (default values) of [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), [default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields), etc., will inherit the name of the bound identifier as their `name`. ```js const [f = () => {}] = []; f.name; // "f" const { someMethod: m = () => {} } = {}; m.name; // "m" function foo(f = () => {}) { console.log(f.name); } foo(); // "f" class Foo { static someMethod = () => {}; } Foo.someMethod.name; // someMethod ``` ### Shorthand method ```js const o = { foo() {}, }; o.foo.name; // "foo"; ``` ### Bound function {{jsxref("Function.prototype.bind()")}} produces a function whose name is "bound " plus the function name. ```js function foo() {} foo.bind({}).name; // "bound foo" ``` ### Getter and setter When using [`get`](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [`set`](/en-US/docs/Web/JavaScript/Reference/Functions/set) accessor properties, "get" or "set" will appear in the function name. ```js const o = { get foo() {}, set foo(x) {}, }; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; ``` ### Class A class's name follows the same algorithm as function declarations and expressions. ```js class Foo {} Foo.name; // "Foo" ``` > **Warning:** JavaScript will set the function's `name` property only if a function does not have an own property called `name`. However, classes' [static members](/en-US/docs/Web/JavaScript/Reference/Classes/static) will be set as own properties of the class constructor function, and thus prevent the built-in `name` from being applied. See [an example](#telling_the_constructor_name_of_an_object) below. ### Symbol as function name If a {{jsxref("Symbol")}} is used a function name and the symbol has a description, the method's name is the description in square brackets. ```js const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = { [sym1]() {}, [sym2]() {}, }; o[sym1].name; // "[foo]" o[sym2].name; // "[]" ``` ### Private property Private fields and private methods have the hash (`#`) as part of their names. ```js class Foo { #field = () => {}; #method() {} getNames() { console.log(this.#field.name); console.log(this.#method.name); } } new Foo().getNames(); // "#field" // "#method" ``` ## Examples ### Telling the constructor name of an object You can use `obj.constructor.name` to check the "class" of an object. ```js function Foo() {} // Or: class Foo {} const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // "Foo" ``` However, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a static method property `name()`: ```js class Foo { constructor() {} static name() {} } ``` With a `static name()` method `Foo.name` no longer holds the actual class name but a reference to the `name()` function object. Trying to obtain the class of `fooInstance` via `fooInstance.constructor.name` won't give us the class name at all, but instead a reference to the static class method. Example: ```js const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // ƒ name() {} ``` Due to the existence of static fields, `name` may not be a function either. ```js class Foo { static name = 123; } console.log(new Foo().constructor.name); // 123 ``` If a class has a static property called `name`, it will also become _writable_. The built-in definition in the absence of a custom static definition is _read-only_: ```js Foo.name = "Hello"; console.log(Foo.name); // "Hello" if class Foo has a static "name" property, but "Foo" if not. ``` Therefore you may not rely on the built-in `name` property to always hold a class's name. ### JavaScript compressors and minifiers > **Warning:** Be careful when using the `name` property with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time. Source code such as: ```js function Foo() {} const foo = new Foo(); if (foo.constructor.name === "Foo") { console.log("'foo' is an instance of 'Foo'"); } else { console.log("Oops!"); } ``` may be compressed to: ```js function a() {} const b = new a(); if (b.constructor.name === "Foo") { console.log("'foo' is an instance of 'Foo'"); } else { console.log("Oops!"); } ``` In the uncompressed version, the program runs into the truthy branch and logs "'foo' is an instance of 'Foo'" — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the `name` property, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill for `Function: name` in `core-js`](https://github.com/zloirock/core-js#ecmascript-function) - {{jsxref("Function")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/bind/index.md
--- title: Function.prototype.bind() slug: Web/JavaScript/Reference/Global_Objects/Function/bind page-type: javascript-instance-method browser-compat: javascript.builtins.Function.bind --- {{JSRef}} The **`bind()`** method of {{jsxref("Function")}} instances creates a new function that, when called, calls this function with its `this` keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called. {{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}} ## Syntax ```js-nolint bind(thisArg) bind(thisArg, arg1) bind(thisArg, arg1, arg2) bind(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to be passed as the `this` parameter to the target function `func` when the bound function is called. If the function is not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the {{jsxref("Operators/new", "new")}} operator. - `arg1`, …, `argN` {{optional_inline}} - : Arguments to prepend to arguments provided to the bound function when invoking `func`. ### Return value A copy of the given function with the specified `this` value, and initial arguments (if provided). ## Description The `bind()` function creates a new _bound function_. Calling the bound function generally results in the execution of the function it wraps, which is also called the _target function_. The bound function will store the parameters passed — which include the value of `this` and the first few arguments — as its internal state. These values are stored in advance, instead of being passed at call time. You can generally see `const boundFn = fn.bind(thisArg, arg1, arg2)` as being equivalent to `const boundFn = (...restArgs) => fn.call(thisArg, arg1, arg2, ...restArgs)` for the effect when it's called (but not when `boundFn` is constructed). A bound function can be further bound by calling `boundFn.bind(thisArg, /* more args */)`, which creates another bound function `boundFn2`. The newly bound `thisArg` value is ignored, because the target function of `boundFn2`, which is `boundFn`, already has a bound `this`. When `boundFn2` is called, it would call `boundFn`, which in turn calls `fn`. The arguments that `fn` ultimately receives are, in order: the arguments bound by `boundFn`, arguments bound by `boundFn2`, and the arguments received by `boundFn2`. ```js "use strict"; // prevent `this` from being boxed into the wrapper object function log(...args) { console.log(this, ...args); } const boundLog = log.bind("this value", 1, 2); const boundLog2 = boundLog.bind("new this value", 3, 4); boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6 ``` A bound function may also be constructed using the {{jsxref("Operators/new", "new")}} operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided `this` value is ignored (because construction prepares its own `this`, as seen by the parameters of {{jsxref("Reflect.construct")}}). If the bound function is directly constructed, [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) will be the target function instead. (That is, the bound function is transparent to `new.target`.) ```js class Base { constructor(...args) { console.log(new.target === Base); console.log(args); } } const BoundBase = Base.bind(null, 1, 2); new BoundBase(3, 4); // true, [1, 2, 3, 4] ``` However, because a bound function does not have the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property, it cannot be used as a base class for [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends). ```js example-bad class Derived extends class {}.bind(null) {} // TypeError: Class extends value does not have valid prototype property undefined ``` When using a bound function as the right-hand side of [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof), `instanceof` would reach for the target function (which is stored internally in the bound function) and read its `prototype` instead. ```js class Base {} const BoundBase = Base.bind(null, 1, 2); console.log(new Base() instanceof BoundBase); // true ``` The bound function has the following properties: - [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) - : The `length` of the target function minus the number of arguments being bound (not counting the `thisArg` parameter), with 0 being the minimum value. - [`name`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) - : The `name` of the target function plus a `"bound "` prefix. The bound function also inherits the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of the target function. However, it doesn't have other own properties of the target function (such as [static properties](/en-US/docs/Web/JavaScript/Reference/Classes/static) if the target function is a class). ## Examples ### Creating a bound function The simplest use of `bind()` is to make a function that, no matter how it is called, is called with a particular `this` value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its `this` (e.g., by using the method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem: ```js // Top-level 'this' is bound to 'globalThis' in scripts. this.x = 9; const module = { x: 81, getX() { return this.x; }, }; // The 'this' parameter of 'getX' is bound to 'module'. console.log(module.getX()); // 81 const retrieveX = module.getX; // The 'this' parameter of 'retrieveX' is bound to 'globalThis' in non-strict mode. console.log(retrieveX()); // 9 // Create a new function 'boundGetX' with the 'this' parameter bound to 'module'. const boundGetX = retrieveX.bind(module); console.log(boundGetX()); // 81 ``` > **Note:** If you run this example in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), the `this` parameter of `retrieveX` will be bound to `undefined` instead of `globalThis`, causing the `retrieveX()` call to fail. > > If you run this example in an ECMAScript module, top-level `this` will be bound to `undefined` instead of `globalThis`, causing the `this.x = 9` assignment to fail. > > If you run this example in a Node CommonJS module, top-level `this` will be bound to `module.exports` instead of `globalThis`. However, the `this` parameter of `retrieveX` will still be bound to `globalThis` in non-strict mode and to `undefined` in strict mode. Therefore, in non-strict mode (the default), the `retrieveX()` call will return `undefined` because `this.x = 9` is writing to a different object (`module.exports`) from what `getX` is reading from (`globalThis`). In fact, some built-in "methods" are also getters that return bound functions — one notable example being [`Intl.NumberFormat.prototype.format()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format#using_format_with_map), which, when accessed, returns a bound function that you can directly pass as a callback. ### Partially applied functions The next simplest use of `bind()` is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided `this` value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed to the bound function at the time it is called. ```js function list(...args) { return args; } function addArguments(arg1, arg2) { return arg1 + arg2; } console.log(list(1, 2, 3)); // [1, 2, 3] console.log(addArguments(1, 2)); // 3 // Create a function with a preset leading argument const leadingThirtySevenList = list.bind(null, 37); // Create a function with a preset first argument. const addThirtySeven = addArguments.bind(null, 37); console.log(leadingThirtySevenList()); // [37] console.log(leadingThirtySevenList(1, 2, 3)); // [37, 1, 2, 3] console.log(addThirtySeven(5)); // 42 console.log(addThirtySeven(5, 10)); // 42 // (the last argument 10 is ignored) ``` ### With setTimeout() By default, within {{domxref("setTimeout()")}}, the `this` keyword will be set to [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), which is {{domxref("window")}} in browsers. When working with class methods that require `this` to refer to class instances, you may explicitly bind `this` to the callback function, in order to maintain the instance. ```js class LateBloomer { constructor() { this.petalCount = Math.floor(Math.random() * 12) + 1; } bloom() { // Declare bloom after a delay of 1 second setTimeout(this.declare.bind(this), 1000); } declare() { console.log(`I am a beautiful flower with ${this.petalCount} petals!`); } } const flower = new LateBloomer(); flower.bloom(); // After 1 second, calls 'flower.declare()' ``` You can also use [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) for this purpose. ```js class LateBloomer { bloom() { // Declare bloom after a delay of 1 second setTimeout(() => this.declare(), 1000); } } ``` ### Bound functions used as constructors Bound functions are automatically suitable for use with the {{jsxref("Operators/new", "new")}} operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided `this` is ignored. However, provided arguments are still prepended to the constructor call. ```js function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return `${this.x},${this.y}`; }; const p = new Point(1, 2); p.toString(); // '1,2' // The thisArg's value doesn't matter because it's ignored const YAxisPoint = Point.bind(null, 0 /*x*/); const axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new YAxisPoint(17, 42) instanceof Point; // true ``` Note that you need not do anything special to create a bound function for use with {{jsxref("Operators/new", "new")}}. [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target), [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof), [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) etc. all work as expected, as if the constructor was never bound. The only difference is that it can no longer be used for [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends). The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}. If you call it without `new`, the bound `this` is suddenly not ignored. ```js const emptyObj = {}; const YAxisPoint = Point.bind(emptyObj, 0 /*x*/); // Can still be called as a normal function // (although usually this is undesirable) YAxisPoint(13); // The modifications to `this` is now observable from the outside console.log(emptyObj); // { x: 0, y: 13 } ``` If you wish to restrict a bound function to only be callable with {{jsxref("Operators/new", "new")}}, or only be callable without `new`, the target function must enforce that restriction, such as by checking `new.target !== undefined` or using a [class](/en-US/docs/Web/JavaScript/Reference/Classes) instead. ### Binding classes Using `bind()` on classes preserves most of the class's semantics, except that all static own properties of the current class are lost. However, because the prototype chain is preserved, you can still access static properties inherited from the parent class. ```js class Base { static baseProp = "base"; } class Derived extends Base { static derivedProp = "derived"; } const BoundDerived = Derived.bind(null); console.log(BoundDerived.baseProp); // "base" console.log(BoundDerived.derivedProp); // undefined console.log(new BoundDerived() instanceof Derived); // true ``` ### Transforming methods to utility functions `bind()` is also helpful in cases where you want to transform a method which requires a specific `this` value to a plain utility function that accepts the previous `this` parameter as a normal parameter. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments)). Take {{jsxref("Array.prototype.slice()")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this: ```js const slice = Array.prototype.slice; // ... slice.call(arguments); ``` Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use `bind()` to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of {{jsxref("Function.prototype.call()")}}, with the `this` value bound to {{jsxref("Array.prototype.slice()")}}. This means that additional `call()` calls can be eliminated: ```js // Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Function.prototype.bind` in `core-js`](https://github.com/zloirock/core-js#ecmascript-function) - {{jsxref("Function.prototype.apply()")}} - {{jsxref("Function.prototype.call()")}} - {{jsxref("Functions", "Functions", "", 1)}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/function/index.md
--- title: Function() constructor slug: Web/JavaScript/Reference/Global_Objects/Function/Function page-type: javascript-constructor browser-compat: javascript.builtins.Function.Function --- {{JSRef}} The **`Function()`** constructor creates {{jsxref("Function")}} objects. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as {{jsxref("Global_Objects/eval", "eval()")}}. However, unlike `eval` (which may have access to the local scope), the `Function` constructor creates functions which execute in the global scope only. {{EmbedInteractiveExample("pages/js/function-constructor.html", "shorter")}} ## Syntax ```js-nolint new Function(functionBody) new Function(arg1, functionBody) new Function(arg1, arg2, functionBody) new Function(arg1, arg2, /* …, */ argN, functionBody) Function(functionBody) Function(arg1, functionBody) Function(arg1, arg2, functionBody) Function(arg1, arg2, /* …, */ argN, functionBody) ``` > **Note:** `Function()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Function` instance. ### Parameters - `arg1`, …, `argN` {{optional_inline}} - : Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain [identifier](/en-US/docs/Glossary/Identifier), [rest parameter](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), or [destructured](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameter, optionally with a [default](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)), or a list of such strings separated with commas. As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: `"x", "theValue = 42", "[a, b] /* numbers */"` — or `"x, theValue = 42, [a, b] /* numbers */"`. (`"x, theValue = 42", "[a, b]"` is also correct, though very confusing to read.) - `functionBody` - : A string containing the JavaScript statements comprising the function definition. ## Description `Function` objects created with the `Function` constructor are parsed when the function is created. This is less efficient than creating a function with a [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) or [function declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function) and calling it within your code, because such functions are parsed with the rest of the code. All arguments passed to the function, except the last, 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. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion: ```js `function anonymous(${args.join(",")} ) { ${functionBody} }`; ``` This is observable by calling the function's [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) method. However, unlike normal [function expressions](/en-US/docs/Web/JavaScript/Reference/Operators/function), the name `anonymous` is not added to the `functionBody`'s scope, since `functionBody` only has access the global scope. If `functionBody` is not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) (the body itself needs to have the `"use strict"` directive since it doesn't inherit the strictness from the context), you may use [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) to refer to the function itself. Alternatively, you can define the recursive part as an inner function: ```js const recursiveFn = new Function( "count", ` (function recursiveFn(count) { if (count < 0) { return; } console.log(count); recursiveFn(count - 1); })(count); `, ); ``` Note that the two dynamic parts of the assembled source — the parameters list `args.join(",")` and `functionBody` — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts. ```js new Function("/*", "*/) {"); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) {*/) {}" ``` ## Examples ### Specifying arguments with the Function constructor The following code creates a `Function` object that takes two arguments. ```js // Example can be run directly in your JavaScript console // Create a function that takes two arguments, and returns the sum of those arguments const adder = new Function("a", "b", "return a + b"); // Call the function adder(2, 6); // 8 ``` The arguments `a` and `b` are formal argument names that are used in the function body, `return a + b`. ### Creating a function object from a function declaration or function expression ```js // The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name // Observe that new Function is called. This is so we can call the function we created directly afterwards const sumOfArray = new Function( "const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray", )(); // call the function sumOfArray([1, 2, 3, 4]); // 10 // If you don't call new Function at the point of creation, you can use the Function.call() method to call it const findLargestNumber = new Function( "function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber", ); // call the function findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]); // 8 // Function declarations do not require a return statement const sayHello = new Function( "return function (name) { return `Hello, ${name}` }", )(); // call the function sayHello("world"); // Hello, world ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function) - [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) - {{jsxref("Functions", "Functions", "", 1)}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/tostring/index.md
--- title: Function.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Function/toString page-type: javascript-instance-method browser-compat: javascript.builtins.Function.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("Function")}} instances returns a string representing the source code of this function. {{EmbedInteractiveExample("pages/js/function-tostring.html")}} ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string representing the source code of the function. ## Description The {{jsxref("Function")}} object overrides the `toString()` method inherited from {{jsxref("Object")}}; it does not inherit {{jsxref("Object.prototype.toString")}}. For user-defined `Function` objects, the `toString` method returns a string containing the source text segment which was used to define the function. JavaScript calls the `toString` method automatically when a `Function` is to be represented as a text value, e.g. when a function is concatenated with a string. The `toString()` method will throw a {{jsxref("TypeError")}} exception ("Function.prototype.toString called on incompatible object"), if its `this` value object is not a `Function` object. ```js example-bad Function.prototype.toString.call("foo"); // throws TypeError ``` If the `toString()` method is called on built-in function objects, a function created by {{jsxref("Function.prototype.bind()")}}, or other non-JavaScript functions, then `toString()` returns a _native function string_ which looks like ```plain function someName() { [native code] } ``` For intrinsic object methods and functions, `someName` is the initial name of the function; otherwise its content may be implementation-defined, but will always be in property name syntax, like `[1 + 1]`, `someName`, or `1`. > **Note:** This means using [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) on native function strings is a guaranteed syntax error. If the `toString()` method is called on a function created by the `Function` constructor, `toString()` returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. For example, `Function("a", "b", "return a + b").toString()` will return: ```plain function anonymous(a,b ) { return a + b } ``` Since ES2018, the spec requires the return value of `toString()` to be the exact same source code as it was declared, including any whitespace and/or comments — or, if the host doesn't have the source code available for some reason, requires returning a native function string. Support for this revised behavior can be found in the [compatibility table](#browser_compatibility). ## Examples ### Comparing actual source code and toString results ```js function test(fn) { console.log(fn.toString()); } function f() {} class A { a() {} } function* g() {} test(f); // "function f() {}" test(A); // "class A { a() {} }" test(g); // "function* g() {}" test((a) => a); // "(a) => a" test({ a() {} }.a); // "a() {}" test({ *a() {} }.a); // "*a() {}" test({ [0]() {} }[0]); // "[0]() {}" test(Object.getOwnPropertyDescriptor({ get a() {} }, "a").get); // "get a() {}" test(Object.getOwnPropertyDescriptor({ set a(x) {} }, "a").set); // "set a(x) {}" test(Function.prototype.toString); // "function toString() { [native code] }" test(function f() {}.bind(0)); // "function () { [native code] }" test(Function("a", "b")); // function anonymous(a\n) {\nb\n} ``` Note that after the `Function.prototype.toString()` revision, when `toString()` is called, implementations are never allowed to synthesize a function's source that is not a native function string. The method always returns the exact source code used to create the function — including the [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) examples above. The [`Function`](/en-US/docs/Web/JavaScript/Reference/Functions) constructor itself has the capability of synthesizing the source code for the function (and is therefore a form of implicit [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)). ### Getting source text of a function It is possible to get the source text of a function by coercing it to a string — for example, by wrapping it in a template literal: ```js function foo() { return "bar"; } console.log(`${foo}`); // function foo() { // return "bar"; // } ``` This source text is _exact_, including any interspersed comments (which won't be stored by the engine's internal representation otherwise). ```js function foo /* a comment */() { return "bar"; } console.log(foo.toString()); // function foo /* a comment */() { // return "bar"; // } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/displayname/index.md
--- title: "Function: displayName" slug: Web/JavaScript/Reference/Global_Objects/Function/displayName page-type: javascript-instance-data-property status: - non-standard browser-compat: javascript.builtins.Function.displayName --- {{JSRef}} {{Non-standard_Header}} The optional **`displayName`** property of a {{jsxref("Function")}} instance specifies the display name of the function. ## Value The `displayName` property is not initially present on any function — it's added by the code authors. For the purpose of display, it should be a string. ## Description The `displayName` property, if present, may be preferred by consoles and profilers over the {{jsxref("Function/name", "name")}} property to be displayed as the name of a function. Among browsers, only the Firefox console utilizes this property. React devtools also use the [`displayName`](https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging) property when displaying the component tree. Firefox does some basic attempts to decode the `displayName` that's possibly generated by the [anonymous JavaScript functions naming convention](https://johnjbarton.github.io/nonymous/index.html) algorithm. The following patterns are detected: - If `displayName` ends with a sequence of alphanumeric characters, `_`, and `$`, the longest such suffix is displayed. - If `displayName` ends with a sequence of `[]`-enclosed characters, that sequence is displayed without the square brackets. - If `displayName` ends with a sequence of alphanumeric characters and `_` followed by some `/`, `.`, or `<`, the sequence is returned without the trailing `/`, `.`, or `<` characters. - If `displayName` ends with a sequence of alphanumeric characters and `_` followed by `(^)`, the sequence is displayed without the `(^)`. If none of the above patterns match, the entire `displayName` is displayed. ## Examples ### Setting a displayName By entering the following in a Firefox console, it should display as something like `function MyFunction()`: ```js const a = function () {}; a.displayName = "MyFunction"; a; // function MyFunction() ``` ### Changing displayName dynamically You can dynamically change the `displayName` of a function: ```js const object = { // anonymous someMethod: function someMethod(value) { someMethod.displayName = `someMethod (${value})`; }, }; console.log(object.someMethod.displayName); // undefined object.someMethod("123"); console.log(object.someMethod.displayName); // "someMethod (123)" ``` ### Cleaning of displayName Firefox devtools would clean up a few common patterns in the `displayName` property before displaying it. ```js function foo() {} function testName(name) { foo.displayName = name; console.log(foo); } testName("$foo$"); // function $foo$() testName("foo bar"); // function bar() testName("Foo.prototype.add"); // function add() testName("foo ."); // function foo .() testName("foo <"); // function foo <() testName("foo?"); // function foo?() testName("foo()"); // function foo()() testName("[...]"); // function ...() testName("foo<"); // function foo() testName("foo..."); // function foo() testName("foo(^)"); // function foo() ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Function.prototype.name")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/length/index.md
--- title: "Function: length" slug: Web/JavaScript/Reference/Global_Objects/Function/length page-type: javascript-instance-data-property browser-compat: javascript.builtins.Function.length --- {{JSRef}} The **`length`** data property of a {{jsxref("Function")}} instance indicates the number of parameters expected by the function. {{EmbedInteractiveExample("pages/js/function-length.html")}} ## Value A number. {{js_property_attributes(0, 0, 1)}} ## Description A {{jsxref("Function")}} object's `length` property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the {{jsxref("Functions/rest_parameters", "rest parameter", "", 1)}} and only includes parameters before the first one with a default value. By contrast, {{jsxref("Functions/arguments/length", "arguments.length")}} is local to a function and provides the number of arguments actually passed to the function. The {{jsxref("Function")}} constructor is itself a `Function` object. Its `length` data property has a value of `1`. Due to historical reasons, `Function.prototype` is a callable itself. The `length` property of `Function.prototype` has a value of `0`. ## Examples ### Using function length ```js console.log(Function.length); // 1 console.log((() => {}).length); // 0 console.log(((a) => {}).length); // 1 console.log(((a, b) => {}).length); // 2 etc. console.log(((...args) => {}).length); // 0, rest parameter is not counted console.log(((a, b = 1, c) => {}).length); // 1, only parameters before the first one with // a default value are counted ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Function")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/call/index.md
--- title: Function.prototype.call() slug: Web/JavaScript/Reference/Global_Objects/Function/call page-type: javascript-instance-method browser-compat: javascript.builtins.Function.call --- {{JSRef}} The **`call()`** method of {{jsxref("Function")}} instances calls this function with a given `this` value and arguments provided individually. {{EmbedInteractiveExample("pages/js/function-call.html")}} ## Syntax ```js-nolint call(thisArg) call(thisArg, arg1) call(thisArg, arg1, arg2) call(thisArg, arg1, arg2, /* …, */ argN) ``` ### Parameters - `thisArg` - : The value to use as `this` when calling `func`. If the function is not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) will be replaced with the global object, and primitive values will be converted to objects. - `arg1`, …, `argN` {{optional_inline}} - : Arguments for the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to {{jsxref("Function/apply", "apply()")}}, except that the function arguments are passed to `call()` individually as a list, while for `apply()` they are combined in one object, typically an array — for example, `func.call(this, "eat", "bananas")` vs. `func.apply(this, ["eat", "bananas"])`. Normally, when calling a function, the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `call()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. > **Warning:** Do not use `call()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Use {{jsxref("Reflect.construct()")}} or [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) instead. ## Examples ### Using call() to invoke a function and specifying the this value In the example below, when we call `greet`, the value of `this` will be bound to object `obj`, even when `greet` is not a method of `obj`. ```js function greet() { console.log(this.animal, "typically sleep between", this.sleepDuration); } const obj = { animal: "cats", sleepDuration: "12 and 16 hours", }; greet.call(obj); // cats typically sleep between 12 and 16 hours ``` ### Using call() to invoke a function without specifying the first argument If the first `thisArg` parameter is omitted, it defaults to `undefined`. In non-strict mode, the `this` value is then substituted with {{jsxref("globalThis")}} (which is akin to the global object). ```js globalThis.globProp = "Wisen"; function display() { console.log(`globProp value is ${this.globProp}`); } display.call(); // Logs "globProp value is Wisen" ``` In strict mode, the value of `this` is not substituted, so it stays as `undefined`. ```js "use strict"; globalThis.globProp = "Wisen"; function display() { console.log(`globProp value is ${this.globProp}`); } display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined ``` ### Transforming methods to utility functions `call()` is almost equivalent to a normal function call, except that `this` is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling `array.map(callback)`, you use `map(array, callback)`, which avoids mutating `Array.prototype`, and allows you to use `map` with array-like objects that are not arrays (for example, [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments)). Take {{jsxref("Array.prototype.slice()")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this: ```js const slice = Array.prototype.slice; // ... slice.call(arguments); ``` Note that you can't save `slice.call` and call it as a plain function, because the `call()` method also reads its `this` value, which is the function it should call. In this case, you can use {{jsxref("Function/bind", "bind()")}} to bind the value of `this` for `call()`. In the following piece of code, `slice()` is a bound version of {{jsxref("Function.prototype.call()")}}, with the `this` value bound to {{jsxref("Array.prototype.slice()")}}. This means that additional `call()` calls can be eliminated: ```js // Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Function.prototype.bind()")}} - {{jsxref("Function.prototype.apply()")}} - {{jsxref("Reflect.apply()")}} - [Spread syntax (`...`)](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) - [Introduction to Object-Oriented JavaScript](/en-US/docs/Learn/JavaScript/Objects)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/prototype/index.md
--- title: "Function: prototype" slug: Web/JavaScript/Reference/Global_Objects/Function/prototype page-type: javascript-instance-data-property spec-urls: https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-function-instances-prototype --- {{JSRef}} The **`prototype`** data property of a {{jsxref("Function")}} instance is used when the function is used as a constructor with the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator. It will become the new object's prototype. > **Note:** Not all {{jsxref("Function")}} objects have the `prototype` property — see [description](#description). ## Value An object. {{js_property_attributes(1, 0, 0)}} > **Note:** The `prototype` property of [classes](/en-US/docs/Web/JavaScript/Reference/Classes) is not writable. ## Description When a function is called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), the constructor's `prototype` property will become the resulting object's prototype. ```js function Ctor() {} const inst = new Ctor(); console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true ``` You can read [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors) for more information about the interactions between a constructor function's `prototype` property and the resulting object's prototype. A function having a `prototype` property is not sufficient for it to be eligible as a constructor. [Generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*) have a `prototype` property, but cannot be called with `new`: ```js async function* asyncGeneratorFunction() {} function* generatorFunction() {} ``` Instead, generator functions' `prototype` property is used when they are called _without_ `new`. The `prototype` property will become the returned [`Generator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) object's prototype. In addition, some functions may have a `prototype` but throw unconditionally when called with `new`. For example, the [`Symbol()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/Symbol) and [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) functions throw when called with `new`, because `Symbol.prototype` and `BigInt.prototype` are only intended to provide methods for the primitive values, but the wrapper objects should not be directly constructed. The following functions do not have `prototype`, and are therefore ineligible as constructors, even if a `prototype` property is later manually assigned: ```js const method = { foo() {} }.foo; const arrowFunction = () => {}; async function asyncFunction() {} ``` The following are valid constructors that have `prototype`: ```js class Class {} function fn() {} ``` A [bound function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) does not have a `prototype` property, but may be constructable. When it's constructed, the target function is constructed instead, and if the target function is constructable, it would return a normal instance. ```js const boundFunction = function () {}.bind(null); ``` A function's `prototype` property, by default, is a plain object with one property: [`constructor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor), which is a reference to the function itself. The `constructor` property is writable, non-enumerable, and configurable. If the `prototype` of a function is reassigned with something other than an {{jsxref("Object")}}, when the function is called with `new`, the returned object's prototype would be `Object.prototype` instead. (In other words, `new` ignores the `prototype` property and constructs a plain object.) ```js function Ctor() {} Ctor.prototype = 3; console.log(Object.getPrototypeOf(new Ctor()) === Object.prototype); // true ``` ## Examples ### Changing the prototype of all instances by mutating the prototype property ```js function Ctor() {} const p1 = new Ctor(); const p2 = new Ctor(); Ctor.prototype.prop = 1; console.log(p1.prop); // 1 console.log(p2.prop); // 1 ``` ### Adding a non-method property to a class's prototype property [Class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) add properties to each instance. Class methods declare _function_ properties on the prototype. However, there's no way to add a non-function property to the prototype. In case you want to share static data between all instances (for example, [`Error.prototype.name`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name) is the same between all error instances), you can manually assign it on the `prototype` of a class. ```js class Dog { constructor(name) { this.name = name; } } Dog.prototype.species = "dog"; console.log(new Dog("Jack").species); // "dog" ``` This can be made more ergonomic using [static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks), which are called when the class is initialized. ```js class Dog { static { Dog.prototype.species = "dog"; } constructor(name) { this.name = name; } } console.log(new Dog("Jack").species); // "dog" ``` ## Specifications {{Specifications}} ## See also - {{jsxref("Function")}} - [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#constructors)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/arguments/index.md
--- title: Function.prototype.arguments slug: Web/JavaScript/Reference/Global_Objects/Function/arguments page-type: javascript-instance-accessor-property status: - deprecated - non-standard browser-compat: javascript.builtins.Function.arguments --- {{JSRef}}{{Deprecated_Header}}{{Non-standard_Header}} > **Note:** The `arguments` property of {{jsxref("Function")}} objects is deprecated. The recommended way to access the `arguments` object is to refer to the variable {{jsxref("Functions/arguments", "arguments")}} available within functions. The **`arguments`** accessor property of {{jsxref("Function")}} instances returns the arguments passed to this function. For [strict](/en-US/docs/Web/JavaScript/Reference/Strict_mode), arrow, async, and generator functions, accessing the `arguments` property throws a {{jsxref("TypeError")}}. ## Description The value of `arguments` is an array-like object corresponding to the arguments passed to a function. In the case of recursion, i.e. if function `f` appears several times on the call stack, the value of `f.arguments` represents the arguments corresponding to the most recent invocation of the function. The value of the `arguments` property is normally {{jsxref("Operators/null", "null")}} if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned). Note that the only behavior specified by the ECMAScript specification is that `Function.prototype` has an initial `arguments` accessor that unconditionally throws a {{jsxref("TypeError")}} for any `get` or `set` request (known as a "poison pill accessor"), and that implementations are not allowed to change this semantic for any function except non-strict plain functions. The actual behavior of the `arguments` property, if it's anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill `Function.prototype.arguments` accessor to specially handle `this` values that are non-strict functions. ```js (function f() { if (Object.hasOwn(f, "arguments")) { console.log( "arguments is an own property with descriptor", Object.getOwnPropertyDescriptor(f, "arguments"), ); } else { console.log( "f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments", ); console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(f), "arguments", ).get.call(f), ); } })(); // In Chrome: // arguments is an own property with descriptor {value: Arguments(0), writable: false, enumerable: false, configurable: false} // In Firefox: // f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments // Arguments { … } ``` ## Examples ### Using the arguments property ```js function f(n) { g(n - 1); } function g(n) { console.log(`before: ${g.arguments[0]}`); if (n > 0) { f(n); } console.log(`after: ${g.arguments[0]}`); } f(2); console.log(`returned: ${g.arguments}`); // Logs: // before: 1 // before: 0 // after: 0 // after: 1 // returned: null ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Functions/arguments", "arguments")}} - [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/@@hasinstance/index.md
--- title: Function.prototype[@@hasInstance]() slug: Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance page-type: javascript-instance-method browser-compat: javascript.builtins.Function.@@hasInstance --- {{JSRef}} The **`[@@hasInstance]()`** method of {{jsxref("Function")}} instances specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor's instances. It is called by the [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator. ## Syntax ```js-nolint func[Symbol.hasInstance](value) ``` ### Parameters - `value` - : The object to test. Primitive values always return `false`. ### Return value `true` if `func.prototype` is in the prototype chain of `value`; otherwise, `false`. Always returns `false` if `value` is not an object or `this` is not a function. If `this` is a [bound function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), returns the result of a `instanceof` test on `value` and the underlying target function. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `this` is not a bound function and `this.prototype` is not an object. ## Description The [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator calls the [`[@@hasInstance]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) method of the right-hand side whenever such a method exists. Because all functions inherit from `Function.prototype` by default, they would all have the `[@@hasInstance]()` method, so most of the time, the `Function.prototype[@@hasInstance]` method specifies the behavior of `instanceof` when the right-hand side is a function. This method implements the default behavior of the `instanceof` operator (the same algorithm when `constructor` has no `@@hasInstance` method). Unlike most methods, the `Function.prototype[@@hasInstance]()` property is non-configurable and non-writable. This is a security feature to prevent the underlying target function of a bound function from being obtainable. See [this StackOverflow answer](https://stackoverflow.com/questions/38215027/trying-to-understand-the-official-es6-spec-regarding-symbol-hasinstance/38215392#38215392) for an example. ## Examples ### Reverting to default instanceof behavior You would rarely need to call this method directly. Instead, this method is called by the `instanceof` operator. You should expect the two results to usually be equivalent. ```js class Foo {} const foo = new Foo(); console.log(foo instanceof Foo === Foo[Symbol.hasInstance](foo)); // true ``` You may want to use this method if you want to invoke the default `instanceof` behavior, but you don't know if a constructor has a overridden `[@@hasInstance]()` method. ```js class Foo { static [Symbol.hasInstance](value) { // A custom implementation return false; } } const foo = new Foo(); console.log(foo instanceof Foo); // false console.log(Function.prototype[Symbol.hasInstance].call(Foo, foo)); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) - {{jsxref("Symbol.hasInstance")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function
data/mdn-content/files/en-us/web/javascript/reference/global_objects/function/apply/index.md
--- title: Function.prototype.apply() slug: Web/JavaScript/Reference/Global_Objects/Function/apply page-type: javascript-instance-method browser-compat: javascript.builtins.Function.apply --- {{JSRef}} The **`apply()`** method of {{jsxref("Function")}} instances calls this function with a given `this` value, and `arguments` provided as an array (or an [array-like object](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)). {{EmbedInteractiveExample("pages/js/function-apply.html")}} ## Syntax ```js-nolint apply(thisArg) apply(thisArg, argsArray) ``` ### Parameters - `thisArg` - : The value of `this` provided for the call to `func`. If the function is not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) and [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) will be replaced with the global object, and primitive values will be converted to objects. - `argsArray` {{optional_inline}} - : An array-like object, specifying the arguments with which `func` should be called, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) if no arguments should be provided to the function. ### Return value The result of calling the function with the specified `this` value and arguments. ## Description > **Note:** This function is almost identical to {{jsxref("Function/call", "call()")}}, except that the function arguments are passed to `call()` individually as a list, while for `apply()` they are combined in one object, typically an array — for example, `func.call(this, "eat", "bananas")` vs. `func.apply(this, ["eat", "bananas"])`. Normally, when calling a function, the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) inside the function is the object that the function was accessed on. With `apply()`, you can assign an arbitrary value as `this` when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions. You can also use any kind of object which is array-like as the second parameter. In practice, this means that it needs to have a `length` property, and integer ("index") properties in the range `(0..length - 1)`. For example, you could use a {{domxref("NodeList")}}, or a custom object like `{ 'length': 2, '0': 'eat', '1': 'bananas' }`. You can also use {{jsxref("Functions/arguments", "arguments")}}, for example: ```js function wrapper() { return anotherFn.apply(null, arguments); } ``` With the [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) and parameter [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), this can be rewritten as: ```js function wrapper(...args) { return anotherFn(...args); } ``` In general, `fn.apply(null, args)` is equivalent to `fn(...args)` with the parameter spread syntax, except `args` is expected to be an array-like object in the former case with `apply()`, and an [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) object in the latter case with spread syntax. > **Warning:** Do not use `apply()` to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) is `undefined`, and classes throw an error because they can't be called without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Use {{jsxref("Reflect.construct()")}} or [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends) instead. ## Examples ### Using apply() to append an array to another You can use {{jsxref("Array.prototype.push()")}} to append an element to an array. Because `push()` accepts a variable number of arguments, you can also push multiple elements at once. But if you pass an array to `push()`, it will actually add that array as a single element, instead of adding the elements individually, ending up with an array inside an array. On the other hand, {{jsxref("Array.prototype.concat()")}} does have the desired behavior in this case, but it does not append to the _existing_ array — it creates and returns a new array. In this case, you can use `apply` to implicitly "spread" an array as a series of arguments. ```js const array = ["a", "b"]; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] ``` The same effect can be achieved with the spread syntax. ```js const array = ["a", "b"]; const elements = [0, 1, 2]; array.push(...elements); console.info(array); // ["a", "b", 0, 1, 2] ``` ### Using apply() and built-in functions Clever usage of `apply()` allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax). For example, we can use {{jsxref("Math.max()")}} and {{jsxref("Math.min()")}} to find out the maximum and minimum value in an array. ```js // min/max number in an array const numbers = [5, 6, 2, 3, 7]; // using Math.min/Math.max apply let max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], …) // or Math.max(5, 6, …) let min = Math.min.apply(null, numbers); // vs. simple loop based algorithm max = -Infinity; min = +Infinity; for (let i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } ``` But beware: by using `apply()` (or the spread syntax) with an arbitrarily long arguments list, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of calling a function with too many arguments (that is, more than tens of thousands of arguments) is unspecified and varies across engines. (The JavaScriptCore engine has a hard-coded [argument limit of 65536](https://webkit.org/b/80797).) Most engines throw an exception; but there's no normative specification preventing other behaviors, such as arbitrarily limiting the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments `5, 6, 2, 3` had been passed to `apply` in the examples above, rather than the full array. If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time: ```js function minOfArray(arr) { let min = Infinity; const QUANTUM = 32768; for (let i = 0; i < arr.length; i += QUANTUM) { const submin = Math.min.apply( null, arr.slice(i, Math.min(i + QUANTUM, arr.length)), ); min = Math.min(submin, min); } return min; } const min = minOfArray([5, 6, 2, 3, 7]); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Functions/arguments", "arguments")}} - {{jsxref("Function.prototype.bind()")}} - {{jsxref("Function.prototype.call()")}} - {{jsxref("Reflect.apply()")}} - [Functions](/en-US/docs/Web/JavaScript/Reference/Functions) - [Spread syntax (`...`)](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int8array/index.md
--- title: Int8Array slug: Web/JavaScript/Reference/Global_Objects/Int8Array page-type: javascript-class browser-compat: javascript.builtins.Int8Array --- {{JSRef}} The **`Int8Array`** typed array represents an array of 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). `Int8Array` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("Int8Array/Int8Array", "Int8Array()")}} - : Creates a new `Int8Array` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int8Array.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `1` in the case of `Int8Array`. ## Static methods _Inherits static methods from its parent {{jsxref("TypedArray")}}_. ## Instance properties _Also inherits instance properties from its parent {{jsxref("TypedArray")}}_. These properties are defined on `Int8Array.prototype` and shared by all `Int8Array` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int8Array.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `1` in the case of a `Int8Array`. - {{jsxref("Object/constructor", "Int8Array.prototype.constructor")}} - : The constructor function that created the instance object. For `Int8Array` instances, the initial value is the {{jsxref("Int8Array/Int8Array", "Int8Array")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("TypedArray")}}_. ## Examples ### Different ways to create an Int8Array ```js // From a length const int8 = new Int8Array(2); int8[0] = 42; console.log(int8[0]); // 42 console.log(int8.length); // 2 console.log(int8.BYTES_PER_ELEMENT); // 1 // From an array const x = new Int8Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Int8Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(8); const z = new Int8Array(buffer, 1, 4); console.log(z.byteOffset); // 1 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const int8FromIterable = new Int8Array(iterable); console.log(int8FromIterable); // Int8Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Int8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int8array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int8array/int8array/index.md
--- title: Int8Array() constructor slug: Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array page-type: javascript-constructor browser-compat: javascript.builtins.Int8Array.Int8Array --- {{JSRef}} The **`Int8Array()`** constructor creates {{jsxref("Int8Array")}} objects. The contents are initialized to `0`. ## Syntax ```js-nolint new Int8Array() new Int8Array(length) new Int8Array(typedArray) new Int8Array(object) new Int8Array(buffer) new Int8Array(buffer, byteOffset) new Int8Array(buffer, byteOffset, length) ``` > **Note:** `Int8Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ## Examples ### Different ways to create an Int8Array ```js // From a length const int8 = new Int8Array(2); int8[0] = 42; console.log(int8[0]); // 42 console.log(int8.length); // 2 console.log(int8.BYTES_PER_ELEMENT); // 1 // From an array const x = new Int8Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Int8Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(8); const z = new Int8Array(buffer, 1, 4); console.log(z.byteOffset); // 1 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const int8FromIterable = new Int8Array(iterable); console.log(int8FromIterable); // Int8Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Int8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/index.md
--- title: BigInt slug: Web/JavaScript/Reference/Global_Objects/BigInt page-type: javascript-class browser-compat: javascript.builtins.BigInt --- {{JSRef}} **`BigInt`** values represent numeric values which are [too large](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) to be represented by the `number` {{Glossary("Primitive", "primitive")}}. ## Description A **BigInt value**, also sometimes just called a **BigInt**, is a `bigint` {{Glossary("Primitive", "primitive")}}, created by appending `n` to the end of an integer literal, or by calling the {{jsxref("BigInt/BigInt", "BigInt()")}} function (without the `new` operator) and giving it an integer value or string value. ```js const previouslyMaxSafeInteger = 9007199254740991n; const alsoHuge = BigInt(9007199254740991); // 9007199254740991n const hugeString = BigInt("9007199254740991"); // 9007199254740991n const hugeHex = BigInt("0x1fffffffffffff"); // 9007199254740991n const hugeOctal = BigInt("0o377777777777777777"); // 9007199254740991n const hugeBin = BigInt( "0b11111111111111111111111111111111111111111111111111111", ); // 9007199254740991n ``` BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in [`Math`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value. ### Type information When tested against `typeof`, a BigInt value (`bigint` primitive) will give `"bigint"`: ```js typeof 1n === "bigint"; // true typeof BigInt("1") === "bigint"; // true ``` A BigInt value can also be wrapped in an `Object`: ```js typeof Object(1n) === "object"; // true ``` ### Operators Most operators support BigInts, however most do not permit operands to be of mixed types — both operands must be BigInt or neither: - [Arithmetic operators](/en-US/docs/Web/JavaScript/Reference/Operators#arithmetic_operators): `+`, `-`, `*`, `/`, `%`, `**` - [Bitwise operators](/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators): `>>`, `<<`, `&`, `|`, `^`, `~` - [Unary negation (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation) - [Increment/decrement](/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement): `++`, `--` The boolean-returning operators allow mixing numbers and BigInts as operands: - [Relational operators](/en-US/docs/Web/JavaScript/Reference/Operators#relational_operators) and [equality operators](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators): `>`, `<`, `>=`, `<=`, `==`, `!=`, `===`, `!==` - [Logical operators](/en-US/docs/Web/JavaScript/Reference/Operators#binary_logical_operators) only rely on the [truthiness](/en-US/docs/Glossary/Truthy) of operands A couple of operators do not support BigInt at all: - [Unary plus (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) cannot be supported due to conflicting usage in asm.js, so it has been left out [in order to not break asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). - [Unsigned right shift (`>>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) is the only bitwise operator that's unsupported, as every BigInt value is signed. Special cases: - Addition (`+`) involving a string and a BigInt returns a string. - Division (`/`) truncates fractional components towards zero, since BigInt is unable to represent fractional quantities. ```js const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n const maxPlusOne = previousMaxSafe + 1n; // 9007199254740992n const theFuture = previousMaxSafe + 2n; // 9007199254740993n, this works now! const multi = previousMaxSafe * 2n; // 18014398509481982n const subtr = multi - 10n; // 18014398509481972n const mod = multi % 10n; // 2n const bigN = 2n ** 54n; // 18014398509481984n bigN * -1n; // -18014398509481984n const expected = 4n / 2n; // 2n const truncated = 5n / 2n; // 2n, not 2.5n ``` ### Comparisons A BigInt value is not strictly equal to a Number value, but it _is_ loosely so: ```js 0n === 0; // false 0n == 0; // true ``` A Number value and a BigInt value may be compared as usual: ```js 1n < 2; // true 2n > 1; // true 2 > 2; // false 2n > 2; // false 2n >= 2; // true ``` BigInt values and Number values may be mixed in arrays and sorted: ```js const mixed = [4n, 6, -12n, 10, 4, 0, 0n]; // [4n, 6, -12n, 10, 4, 0, 0n] mixed.sort(); // default sorting behavior // [ -12n, 0, 0n, 10, 4n, 4, 6 ] mixed.sort((a, b) => a - b); // won't work since subtraction will not work with mixed types // TypeError: can't convert BigInt value to Number value // sort with an appropriate numeric comparator mixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); // [ -12n, 0, 0n, 4n, 4, 6, 10 ] ``` Note that comparisons with `Object`-wrapped BigInt values act as with other objects, only indicating equality when the same object instance is compared: ```js Object(0n) === 0n; // false Object(0n) === Object(0n); // false const o = Object(0n); o === o; // true ``` Because coercing between Number values and BigInt values can lead to loss of precision, the following are recommended: - Only use a BigInt value when values greater than 2<sup>53</sup> are reasonably expected. - Don't coerce between BigInt values and Number values. ### Conditionals A BigInt value follows the same conversion rules as Numbers when: - it is converted to a [`Boolean`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean): via the [`Boolean`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) function; - when used with [logical operators](/en-US/docs/Web/JavaScript/Reference/Operators) `||`, `&&`, and `!`; or - within a conditional test like an [`if`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statement. Namely, only `0n` is [falsy](/en-US/docs/Glossary/Falsy); everything else is [truthy](/en-US/docs/Glossary/Truthy). ```js if (0n) { console.log("Hello from the if!"); } else { console.log("Hello from the else!"); } // "Hello from the else!" 0n || 12n; // 12n 0n && 12n; // 0n Boolean(0n); // false Boolean(12n); // true !12n; // false !0n; // true ``` ### Cryptography The operations supported on BigInt values are not constant-time and are thus open to [timing attacks](https://en.wikipedia.org/wiki/Timing_attack). JavaScript BigInts therefore could be dangerous for use in cryptography without mitigating factors. As a very generic example, an attacker could measure the time difference between `101n ** 65537n` and `17n ** 9999n`, and deduce the magnitude of secrets, such as private keys, based on the time elapsed. If you still have to use BigInts, take a look at the [Timing attack FAQ](https://timing.attacks.cr.yp.to/programming.html) for general advice regarding the issue. ### Use within JSON Using [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) with any BigInt value will raise a `TypeError`, as BigInt values aren't serialized in JSON by default. However, `JSON.stringify()` specifically leaves a backdoor for BigInt values: it would try to call the BigInt's `toJSON()` method. (It doesn't do so for any other primitive values.) Therefore, you can implement your own `toJSON()` method (which is one of the few cases where patching built-in objects is not explicitly discouraged): ```js BigInt.prototype.toJSON = function () { return this.toString(); }; ``` Instead of throwing, `JSON.stringify()` now produces a string like this: ```js console.log(JSON.stringify({ a: 1n })); // {"a":"1"} ``` If you do not wish to patch `BigInt.prototype`, you can use the [`replacer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter) parameter of `JSON.stringify` to serialize BigInt values: ```js const replacer = (key, value) => typeof value === "bigint" ? value.toString() : value; const data = { number: 1, big: 18014398509481982n, }; const stringified = JSON.stringify(data, replacer); console.log(stringified); // {"number":1,"big":"18014398509481982"} ``` If you have JSON data containing values you know will be large integers, you can use the [`reviver`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter of `JSON.parse` to handle them: ```js const reviver = (key, value) => (key === "big" ? BigInt(value) : value); const payload = '{"number":1,"big":"18014398509481982"}'; const parsed = JSON.parse(payload, reviver); console.log(parsed); // { number: 1, big: 18014398509481982n } ``` > **Note:** While it's possible to make the replacer of `JSON.stringify()` generic and properly serialize BigInt values for all objects, the reviver of `JSON.parse()` must be specific to the payload shape you expect, because the serialization is _lossy_: it's not possible to distinguish between a string that represents a BigInt and a normal string. ### BigInt coercion Many built-in operations that expect BigInts first coerce their arguments to BigInts. [The operation](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tobigint) can be summarized as follows: - BigInts are returned as-is. - [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) throw a {{jsxref("TypeError")}}. - `true` turns into `1n`; `false` turns into `0n`. - Strings are converted by parsing them as if they contain an integer literal. Any parsing failure results in a {{jsxref("SyntaxError")}}. The syntax is a subset of [string numeric literals](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), where decimal points or exponent indicators are not allowed. - [Numbers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) throw a {{jsxref("TypeError")}} to prevent unintended implicit coercion causing loss of precision. - [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) throw a {{jsxref("TypeError")}}. - Objects are first [converted to a primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling their [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. The resulting primitive is then converted to a BigInt. The best way to achieve nearly the same effect in JavaScript is through the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function: `BigInt(x)` uses the same algorithm to convert `x`, except that [Numbers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) don't throw a {{jsxref("TypeError")}}, but are converted to BigInts if they are integers. Note that built-in operations expecting BigInts often truncate the BigInt to a fixed width after coercion. This includes {{jsxref("BigInt.asIntN()")}}, {{jsxref("BigInt.asUintN()")}}, and methods of {{jsxref("BigInt64Array")}} and {{jsxref("BigUint64Array")}}. ## Constructor - {{jsxref("BigInt/BigInt", "BigInt()")}} - : Creates a new BigInt value. ## Static methods - {{jsxref("BigInt.asIntN()")}} - : Clamps a BigInt value to a signed integer value, and returns that value. - {{jsxref("BigInt.asUintN()")}} - : Clamps a BigInt value to an unsigned integer value, and returns that value. ## Instance properties These properties are defined on `BigInt.prototype` and shared by all `BigInt` instances. - {{jsxref("Object/constructor", "BigInt.prototype.constructor")}} - : The constructor function that created the instance object. For `BigInt` instances, the initial value is the {{jsxref("BigInt/BigInt", "BigInt")}} constructor. - `BigInt.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"BigInt"`. This property is used in {{jsxref("Object.prototype.toString()")}}. However, because `BigInt` also has its own [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/toString) method, this property is not used unless you call [`Object.prototype.toString.call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) with a BigInt as `thisArg`. ## Instance methods - {{jsxref("BigInt.prototype.toLocaleString()")}} - : Returns a string with a language-sensitive representation of this BigInt value. Overrides the [`Object.prototype.toLocaleString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString) method. - {{jsxref("BigInt.prototype.toString()")}} - : Returns a string representing this BigInt value in the specified radix (base). Overrides the [`Object.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) method. - {{jsxref("BigInt.prototype.valueOf()")}} - : Returns this BigInt value. Overrides the [`Object.prototype.valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) method. ## Examples ### Calculating Primes ```js // Returns true if the passed BigInt value is a prime number function isPrime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true; } // Takes a BigInt value as an argument, returns nth prime number as a BigInt value function nthPrime(nth) { let maybePrime = 2n; let prime = 0n; while (nth >= 0n) { if (isPrime(maybePrime)) { nth--; prime = maybePrime; } maybePrime++; } return prime; } nthPrime(20n); // 73n ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`Number`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) - [`Number.MAX_SAFE_INTEGER`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/tostring/index.md
--- title: BigInt.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/BigInt/toString page-type: javascript-instance-method browser-compat: javascript.builtins.BigInt.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("BigInt")}} values returns a string representing the specified {{jsxref("BigInt")}} value. The trailing "n" is not part of the string. {{EmbedInteractiveExample("pages/js/bigint-tostring.html")}} ## Syntax ```js-nolint toString() toString(radix) ``` ### Parameters - `radix` {{optional_inline}} - : An integer in the range 2 through 36 specifying the base to use for representing the BigInt value. Defaults to 10. ### Return value A string representing the specified {{jsxref("BigInt")}} value. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `radix` is less than 2 or greater than 36. ## Description The {{jsxref("BigInt")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit {{jsxref("Object.prototype.toString()")}}. For {{jsxref("BigInt")}} values, the `toString()` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified BigInt value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the BigInt value preceded by a `-` sign, **not** the two's complement of the BigInt value. The `toString()` method requires its `this` value to be a `BigInt` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to BigInt values. Because `BigInt` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `BigInt` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, BigInt _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js BigInt.prototype.toString = () => "Overridden"; console.log(`${1n}`); // "1" console.log(`${Object(1n)}`); // "Overridden" ``` ## Examples ### Using toString() ```js 17n.toString(); // "17" 66n.toString(2); // "1000010" 254n.toString(16); // "fe" (-10n).toString(2); // "-1010" (-0xffn).toString(2); // "-11111111" ``` ### Negative-zero BigInt There is no negative-zero `BigInt` as there are no negative zeros in integers. `-0.0` is an IEEE floating-point concept that only appears in the JavaScript [`Number`](/en-US/docs/Web/JavaScript/Data_structures#number_type) type. ```js (-0n).toString(); // "0" BigInt(-0).toString(); // "0" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("BigInt.prototype.toLocaleString()")}} - {{jsxref("BigInt.prototype.valueOf()")}} - {{jsxref("Number.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/bigint/index.md
--- title: BigInt() constructor slug: Web/JavaScript/Reference/Global_Objects/BigInt/BigInt page-type: javascript-constructor browser-compat: javascript.builtins.BigInt.BigInt --- {{JSRef}} The **`BigInt()`** function returns primitive values of type BigInt. ## Syntax ```js-nolint BigInt(value) ``` > **Note:** `BigInt()` can only be called without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to construct it with `new` throws a {{jsxref("TypeError")}}. ### Parameters - `value` - : The value to be converted to a BigInt value. It may be a string, an integer, a boolean, or another `BigInt`. ### Return value A {{jsxref("BigInt")}} value. Number values must be integers and are converted to BigInts. The boolean value `true` becomes `1n`, and `false` becomes `0n`. Strings are parsed as if they are source text for integer literals, which means they can have leading and trailing whitespaces and can be prefixed with `0b`, `0o`, or `0x`. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if the parameter is a non-integral number. - {{jsxref("TypeError")}} - : Thrown in one of the following cases: - The parameter cannot be converted to a primitive. - After conversion to a primitive, the result is {{jsxref("undefined")}}, {{jsxref("Operators/null", "null")}}, {{jsxref("symbol")}}. - {{jsxref("SyntaxError")}} - : Thrown if the parameter is a string that cannot be parsed as a `BigInt`. ## Examples ### Using BigInt() to convert a number to a BigInt `BigInt()` is the only case where a number can be converted to a BigInt without throwing, because it's very explicit. However, only integers are allowed. ```js BigInt(123); // 123n BigInt(123.3); // RangeError: The number 123.3 cannot be converted to a BigInt because it is not an integer ``` ### Using string values ```js BigInt("123"); // 123n BigInt("0b10101"); // 21n, which is 10101 in binary BigInt("0o123"); // 83n, which is 123 in octal BigInt("0x123"); // 291n, which is 123 in hexadecimal BigInt(" 123 "); // 123n, leading and trailing whitespaces are allowed ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/valueof/index.md
--- title: BigInt.prototype.valueOf() slug: Web/JavaScript/Reference/Global_Objects/BigInt/valueOf page-type: javascript-instance-method browser-compat: javascript.builtins.BigInt.valueOf --- {{JSRef}} The **`valueOf()`** method of {{jsxref("BigInt")}} values returns the wrapped primitive value of a {{jsxref("BigInt")}} object. {{EmbedInteractiveExample("pages/js/bigint-valueof.html", "shorter")}} ## Syntax ```js-nolint valueOf() ``` ### Parameters None. ### Return value A BigInt representing the primitive value of the specified {{jsxref("BigInt")}} object. ## Examples ### Using `valueOf` ```js typeof Object(1n); // object typeof Object(1n).valueOf(); // bigint ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("BigInt.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/asuintn/index.md
--- title: BigInt.asUintN() slug: Web/JavaScript/Reference/Global_Objects/BigInt/asUintN page-type: javascript-static-method browser-compat: javascript.builtins.BigInt.asUintN --- {{JSRef}} The **`BigInt.asUintN()`** static method truncates a `BigInt` value to the given number of least significant bits and returns that value as an unsigned integer. {{EmbedInteractiveExample("pages/js/bigint-asuintn.html", "taller")}} ## Syntax ```js-nolint BigInt.asUintN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 2<sup>53</sup> - 1, inclusive. - `bigint` - : The BigInt value to truncate to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as an unsigned integer. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `bits` is negative or greater than 2<sup>53</sup> - 1. ## Description The `BigInt.asUintN` method truncates a `BigInt` value to the given number of bits, and interprets the result as an unsigned integer. Unsigned integers have no sign bits and are always non-negative. For example, for `BigInt.asUintN(4, 25n)`, the value `25n` is truncated to `9n`: ```plain 25n = 00011001 (base 2) ^==== Use only the four remaining bits ===> 1001 (base 2) = 9n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as {{jsxref("Number.prototype.toExponential()")}}, `asUintN` is a static property of {{jsxref("BigInt")}}, so you always use it as `BigInt.asUintN()`, rather than as a method of a BigInt value. Exposing `asUintN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ## Examples ### Staying in 64-bit ranges The `BigInt.asUintN()` method can be useful to stay in the range of 64-bit arithmetic. ```js const max = 2n ** 64n - 1n; BigInt.asUintN(64, max); // 18446744073709551615n BigInt.asUintN(64, max + 1n); // 0n // zero because of overflow: the lowest 64 bits are all zeros ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("BigInt")}} - {{jsxref("BigInt.asIntN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/tolocalestring/index.md
--- title: BigInt.prototype.toLocaleString() slug: Web/JavaScript/Reference/Global_Objects/BigInt/toLocaleString page-type: javascript-instance-method browser-compat: javascript.builtins.BigInt.toLocaleString --- {{JSRef}} The **`toLocaleString()`** method of {{jsxref("BigInt")}} values returns a string with a language-sensitive representation of this BigInt. In implementations with [`Intl.NumberFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) support, this method simply calls `Intl.NumberFormat`. Every time `toLocaleString` is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create a {{jsxref("Intl.NumberFormat")}} object and use its {{jsxref("Intl/NumberFormat/format", "format()")}} method, because a `NumberFormat` object remembers the arguments passed to it and may decide to cache a slice of the database, so future `format` calls can search for localization strings within a more constrained context. {{EmbedInteractiveExample("pages/js/bigint-tolocalestring.html")}} ## Syntax ```js-nolint toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations that support the [`Intl.NumberFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent. - `locales` {{optional_inline}} - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#locales) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used. - `options` {{optional_inline}} - : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for details on these parameters and how to use them. ### Return value A string representing the given BigInt according to language-specific conventions. In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`. > **Note:** Most of the time, the formatting returned by `toLocaleString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleString()` to static values. ## Examples ### Using toLocaleString() Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options. ```js const bigint = 3500n; console.log(bigint.toLocaleString()); // "3,500" if in U.S. English locale ``` ### Checking for support for locales and options parameters The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the {{jsxref("Intl")}} API, you can check the existence of the latter for support: ```js function toLocaleStringSupportsLocales() { return ( typeof Intl === "object" && !!Intl && typeof Intl.NumberFormat === "function" ); } ``` ### Using locales This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument: ```js const bigint = 123456789123456789n; // German uses period for thousands console.log(bigint.toLocaleString("de-DE")); // 123.456.789.123.456.789 // Arabic in most Arabic speaking countries uses Eastern Arabic digits console.log(bigint.toLocaleString("ar-EG")); // ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩ // India uses thousands/lakh/crore separators console.log(bigint.toLocaleString("en-IN")); // 1,23,45,67,89,12,34,56,789 // the nu extension key requests a numbering system, e.g. Chinese decimal console.log(bigint.toLocaleString("zh-Hans-CN-u-nu-hanidec")); // 一二三,四五六,七八九,一二三,四五六,七八九 // when requesting a language that may not be supported, such as // Balinese, include a fallback language, in this case Indonesian console.log(bigint.toLocaleString(["ban", "id"])); // 123.456.789.123.456.789 ``` ### Using options The results provided by `toLocaleString()` can be customized using the `options` parameter: ```js const bigint = 123456789123456789n; // request a currency format console.log( bigint.toLocaleString("de-DE", { style: "currency", currency: "EUR" }), ); // 123.456.789.123.456.789,00 € // the Japanese yen doesn't use a minor unit console.log( bigint.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }), ); // ¥123,456,789,123,456,789 // limit to three significant digits console.log(bigint.toLocaleString("en-IN", { maximumSignificantDigits: 3 })); // 1,23,00,00,00,00,00,00,000 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Intl.NumberFormat")}} - {{jsxref("BigInt.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint
data/mdn-content/files/en-us/web/javascript/reference/global_objects/bigint/asintn/index.md
--- title: BigInt.asIntN() slug: Web/JavaScript/Reference/Global_Objects/BigInt/asIntN page-type: javascript-static-method browser-compat: javascript.builtins.BigInt.asIntN --- {{JSRef}} The **`BigInt.asIntN()`** static method truncates a `BigInt` value to the given number of least significant bits and returns that value as a signed integer. {{EmbedInteractiveExample("pages/js/bigint-asintn.html")}} ## Syntax ```js-nolint BigInt.asIntN(bits, bigint) ``` ### Parameters - `bits` - : The amount of bits available for the returned BigInt. Should be an integer between 0 and 2<sup>53</sup> - 1, inclusive. - `bigint` - : The BigInt value to truncate to fit into the supplied bits. ### Return value The value of `bigint` modulo 2^`bits`, as a signed integer. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `bits` is negative or greater than 2<sup>53</sup> - 1. ## Description The `BigInt.asIntN` method truncates a `BigInt` value to the given number of bits, and interprets the result as a signed integer. For example, for `BigInt.asIntN(3, 25n)`, the value `25n` is truncated to `1n`: ```plain 25n = 00011001 (base 2) ^=== Use only the three remaining bits ===> 001 (base 2) = 1n ``` If the leading bit of the remaining number is `1`, the result is negative. For example, `BigInt.asIntN(4, 25n)` yields `-7n`, because `1001` is the encoding of `-7` under two's complement: ```plain 25n = 00011001 (base 2) ^==== Use only the four remaining bits ===> 1001 (base 2) = -7n ``` > **Note:** `BigInt` values are always encoded as two's complement in binary. Unlike similar language APIs such as {{jsxref("Number.prototype.toExponential()")}}, `asIntN` is a static property of {{jsxref("BigInt")}}, so you always use it as `BigInt.asIntN()`, rather than as a method of a BigInt value. Exposing `asIntN()` as a "standard library function" allows [interop with asm.js](https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs). ## Examples ### Staying in 64-bit ranges The `BigInt.asIntN()` method can be useful to stay in the range of 64-bit arithmetic. ```js const max = 2n ** (64n - 1n) - 1n; BigInt.asIntN(64, max); // 9223372036854775807n BigInt.asIntN(64, max + 1n); // -9223372036854775808n // negative because the 64th bit of 2^63 is 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("BigInt")}} - {{jsxref("BigInt.asUintN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/urierror/index.md
--- title: URIError slug: Web/JavaScript/Reference/Global_Objects/URIError page-type: javascript-class browser-compat: javascript.builtins.URIError --- {{JSRef}} The **`URIError`** object represents an error when a global URI handling function was used in a wrong way. `URIError` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}. `URIError` is a subclass of {{jsxref("Error")}}. ## Constructor - {{jsxref("URIError/URIError", "URIError()")}} - : Creates a new `URIError` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Error")}}_. These properties are defined on `URIError.prototype` and shared by all `URIError` instances. - {{jsxref("Object/constructor", "URIError.prototype.constructor")}} - : The constructor function that created the instance object. For `URIError` instances, the initial value is the {{jsxref("URIError/URIError", "URIError")}} constructor. - {{jsxref("Error/name", "URIError.prototype.name")}} - : Represents the name for the type of error. For `URIError.prototype.name`, the initial value is `"URIError"`. ## Instance methods _Inherits instance methods from its parent {{jsxref("Error")}}_. ## Examples ### Catching an URIError ```js try { decodeURIComponent("%"); } catch (e) { console.log(e instanceof URIError); // true console.log(e.message); // "malformed URI sequence" console.log(e.name); // "URIError" console.log(e.stack); // Stack of the error } ``` ### Creating an URIError ```js try { throw new URIError("Hello"); } catch (e) { console.log(e instanceof URIError); // true console.log(e.message); // "Hello" console.log(e.name); // "URIError" console.log(e.stack); // Stack of the error } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}} - {{jsxref("decodeURI()")}} - {{jsxref("decodeURIComponent()")}} - {{jsxref("encodeURI()")}} - {{jsxref("encodeURIComponent()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/urierror
data/mdn-content/files/en-us/web/javascript/reference/global_objects/urierror/urierror/index.md
--- title: URIError() constructor slug: Web/JavaScript/Reference/Global_Objects/URIError/URIError page-type: javascript-constructor browser-compat: javascript.builtins.URIError.URIError --- {{JSRef}} The **`URIError()`** constructor creates {{jsxref("URIError")}} objects. ## Syntax ```js-nolint new URIError() new URIError(message) new URIError(message, options) new URIError(message, fileName) new URIError(message, fileName, lineNumber) URIError() URIError(message) URIError(message, options) URIError(message, fileName) URIError(message, fileName, lineNumber) ``` > **Note:** `URIError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `URIError` instance. ### Parameters - `message` {{optional_inline}} - : Human-readable description of the error. - `options` {{optional_inline}} - : An object that has the following properties: - `cause` {{optional_inline}} - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. - `fileName` {{optional_inline}} {{non-standard_inline}} - : The name of the file containing the code that caused the exception. - `lineNumber` {{optional_inline}} {{non-standard_inline}} - : The line number of the code that caused the exception. ## Examples ### Catching an URIError ```js try { decodeURIComponent("%"); } catch (e) { console.log(e instanceof URIError); // true console.log(e.message); // "malformed URI sequence" console.log(e.name); // "URIError" console.log(e.stack); // Stack of the error } ``` ### Creating an URIError ```js try { throw new URIError("Hello"); } catch (e) { console.log(e instanceof URIError); // true console.log(e.message); // "Hello" console.log(e.name); // "URIError" console.log(e.stack); // Stack of the error } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}} - {{jsxref("decodeURI()")}} - {{jsxref("decodeURIComponent()")}} - {{jsxref("encodeURI()")}} - {{jsxref("encodeURIComponent()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/index.md
--- title: Set slug: Web/JavaScript/Reference/Global_Objects/Set page-type: javascript-class browser-compat: javascript.builtins.Set --- {{JSRef}} The **`Set`** object lets you store unique values of any type, whether {{Glossary("Primitive", "primitive values")}} or object references. ## Description `Set` objects are collections of values. A value in the set **may only occur once**; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. The _insertion order_ corresponds to the order in which each element was inserted into the set by the [`add()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/add) method successfully (that is, there wasn't an identical element already in the set when `add()` was called). The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N). ### Value equality Value equality is based on the [SameValueZero](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) algorithm. (It used to use [SameValue](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is), which treated `0` and `-0` as different. Check [browser compatibility](#browser_compatibility).) This means {{jsxref("NaN")}} is considered the same as `NaN` (even though `NaN !== NaN`) and all other values are considered equal according to the semantics of the `===` operator. ### Performance The [`has`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has) method checks if a value is in the set, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the set. In particular, it is, on average, faster than the [`Array.prototype.includes`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method when an array has a `length` equal to a set's `size`. ### Set composition The `Set` object provides some methods that allow you to compose sets like you would with mathematical operations. These methods include: <table> <thead> <tr> <th scope="col">Method</th> <th scope="col">Return type</th> <th scope="col">Mathematical equivalent</th> <th scope="col">Venn diagram</th> </tr> </thead> <tbody> <tr> <td>{{jsxref("Set/difference", "A.difference(B)")}}</td> <td><code>Set</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>∖</mo><mi>B</mi></mrow><annotation encoding="TeX">A\setminus B</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="difference/diagram.svg" alt="A Venn diagram where two circles overlap. The difference of A and B is the part of A that is not overlapping B." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/intersection", "A.intersection(B)")}}</td> <td><code>Set</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>∩</mo><mi>B</mi></mrow><annotation encoding="TeX">A\cap B</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="intersection/diagram.svg" alt="A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/symmetricDifference", "A.symmetricDifference(B)")}}</td> <td><code>Set</code></td> <td><math display="inline"><semantics><mrow><mo stretchy="false">(</mo><mi>A</mi><mo>∖</mo><mi>B</mi><mo stretchy="false">)</mo><mo>∪</mo><mo stretchy="false">(</mo><mi>B</mi><mo>∖</mo><mi>A</mi><mo stretchy="false">)</mo></mrow><annotation encoding="TeX">(A\setminus B)\cup(B\setminus A)</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="symmetricDifference/diagram.svg" alt="A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either circle but not both." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/union", "A.union(B)")}}</td> <td><code>Set</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>∪</mo><mi>B</mi></mrow><annotation encoding="TeX">A\cup B</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="union/diagram.svg" alt="A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either or both circles." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/isDisjointFrom", "A.isDisjointFrom(B)")}}</td> <td><code>Boolean</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>∩</mo><mi>B</mi><mo>=</mo><mi>∅</mi></mrow><annotation encoding="TeX">A\cap B = \empty</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="isDisjointFrom/diagram.svg" alt="A Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/isSubsetOf", "A.isSubsetOf(B)")}}</td> <td><code>Boolean</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>⊆</mo><mi>B</mi></mrow><annotation encoding="TeX">A\subseteq B</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="isSubsetOf/diagram.svg" alt="A Venn diragram with two circles. A is a subset of B because A is completely contained in B." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> <tr> <td>{{jsxref("Set/isSupersetOf", "A.isSupersetOf(B)")}}</td> <td><code>Boolean</code></td> <td><math display="inline"><semantics><mrow><mi>A</mi><mo>⊇</mo><mi>B</mi></mrow><annotation encoding="TeX">A\supseteq B</annotation></semantics></math></td> <td style="margin:0;padding:0"><img src="isSupersetOf/diagram.svg" alt="A Venn diagram with two circles. A is a superset of B because B is completely contained in A." style="margin:0;border:0;border-radius:0" width="200" /></td> </tr> </tbody> </table> To make them more generalizable, these methods don't just accept `Set` objects, but anything that's [set-like](#set-like_objects). ### Set-like objects All [set composition methods](#set_composition) require {{jsxref("Operators/this", "this")}} to be an actual `Set` instance, but their arguments just need to be set-like. A _set-like object_ is an object that provides the following: - A {{jsxref("Set/size", "size")}} property that contains a number. - A {{jsxref("Set/has", "has()")}} method that takes an element and returns a boolean. - A {{jsxref("Set/keys", "keys()")}} method that returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of the elements in the set. For example, {{jsxref("Map")}} objects are set-like because they also have {{jsxref("Map/size", "size")}}, {{jsxref("Map/has", "has()")}}, and {{jsxref("Map/keys", "keys()")}}, so they behave just like sets of keys when used in set methods: ```js const a = new Set([1, 2, 3]); const b = new Map([ [1, "one"], [2, "two"], [4, "four"], ]); console.log(a.union(b)); // Set(4) {1, 2, 3, 4} ``` > **Note:** The set-like protocol invokes the `keys()` method instead of [`[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator) to produce elements. This is to make maps valid set-like objects, because for maps, the iterator produces _entries_ but the `has()` method takes _keys_. [Arrays](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) are not set-like because they don't have a `has()` method or the `size` property, and their `keys()` method produces indices instead of elements. {{jsxref("WeakSet")}} objects are also not set-like because they don't have a `keys()` method. ### Set-like browser APIs Browser **`Set`-like objects** (or "setlike objects") are [Web API](/en-US/docs/Web/API) interfaces that behave in many ways like a `Set`. Just like `Set`, elements can be iterated in the same order that they were added to the object. `Set`-like objects and `Set` also have properties and methods that share the same name and behavior. However unlike `Set` they only allow a specific predefined type for each entry. The allowed types are set in the specification IDL definition. For example, {{domxref("GPUSupportedFeatures")}} is a `Set`-like object that must use strings as the key/value. This is defined in the specification IDL below: ```webidl interface GPUSupportedFeatures { readonly setlike<DOMString>; }; ``` `Set`-like objects are either read-only or read-writable (see the `readonly` keyword in the IDL above). - Read-only `Set`-like objects have the property [`size`](#set.prototype.size), and the methods: [`entries()`](#set.prototype.entries), [`forEach()`](#set.prototype.foreach), [`has()`](#set.prototype.has), [`keys()`](#set.prototype.keys), [`values()`](#set.prototype.values), and [`@@iterator`](#set.prototypeiterator). - Writeable `Set`-like objects additionally have the methods: [`clear()`](#set.prototype.clear), [`delete()`](#set.prototype.delete), and [`add()`](#set.prototype.add). The methods and properties have the same behavior as the equivalent entities in `Set`, except for the restriction on the types of the entry. The following are examples of read-only `Set`-like browser objects: - {{domxref("GPUSupportedFeatures")}} - {{domxref("XRAnchorSet")}} The following are examples of writable `Set`-like browser objects: - {{domxref("CustomStateSet")}} - {{domxref("FontFaceSet")}} - {{domxref("Highlight")}} ## Constructor - {{jsxref("Set/Set", "Set()")}} - : Creates a new `Set` object. ## Static properties - {{jsxref("Set/@@species", "Set[@@species]")}} - : The constructor function that is used to create derived objects. ## Instance properties These properties are defined on `Set.prototype` and shared by all `Set` instances. - {{jsxref("Object/constructor", "Set.prototype.constructor")}} - : The constructor function that created the instance object. For `Set` instances, the initial value is the {{jsxref("Set/Set", "Set")}} constructor. - {{jsxref("Set.prototype.size")}} - : Returns the number of values in the `Set` object. - `Set.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Set"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("Set.prototype.add()")}} - : Inserts a new element with a specified value in to a `Set` object, if there isn't an element with the same value already in the `Set`. - {{jsxref("Set.prototype.clear()")}} - : Removes all elements from the `Set` object. - {{jsxref("Set.prototype.delete()")}} - : Removes the element associated to the `value` and returns a boolean asserting whether an element was successfully removed or not. `Set.prototype.has(value)` will return `false` afterwards. - {{jsxref("Set.prototype.difference()")}} - : Takes a set and returns a new set containing elements in this set but not in the given set. - {{jsxref("Set.prototype.entries()")}} - : Returns a new iterator object that contains **an array of `[value, value]`** for each element in the `Set` object, in insertion order. This is similar to the {{jsxref("Map")}} object, so that each entry's _key_ is the same as its _value_ for a `Set`. - {{jsxref("Set.prototype.forEach()")}} - : Calls `callbackFn` once for each value present in the `Set` object, in insertion order. If a `thisArg` parameter is provided, it will be used as the `this` value for each invocation of `callbackFn`. - {{jsxref("Set.prototype.has()")}} - : Returns a boolean asserting whether an element is present with the given value in the `Set` object or not. - {{jsxref("Set.prototype.intersection()")}} - : Takes a set and returns a new set containing elements in both this set and the given set. - {{jsxref("Set.prototype.isDisjointFrom()")}} - : Takes a set and returns a boolean indicating if this set has no elements in common with the given set. - {{jsxref("Set.prototype.isSubsetOf()")}} - : Takes a set and returns a boolean indicating if all elements of this set are in the given set. - {{jsxref("Set.prototype.isSupersetOf()")}} - : Takes a set and returns a boolean indicating if all elements of the given set are in this set. - {{jsxref("Set.prototype.keys()")}} - : An alias for {{jsxref("Set.prototype.values()")}}. - {{jsxref("Set.prototype.symmetricDifference()")}} - : Takes a set and returns a new set containing elements which are in either this set or the given set, but not in both. - {{jsxref("Set.prototype.union()")}} - : Takes a set and returns a new set containing elements which are in either or both of this set and the given set. - {{jsxref("Set.prototype.values()")}} - : Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order. - [`Set.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator) - : Returns a new iterator object that yields the **values** for each element in the `Set` object in insertion order. ## Examples ### Using the Set object ```js const mySet1 = new Set(); mySet1.add(1); // Set(1) { 1 } mySet1.add(5); // Set(2) { 1, 5 } mySet1.add(5); // Set(2) { 1, 5 } mySet1.add("some text"); // Set(3) { 1, 5, 'some text' } const o = { a: 1, b: 2 }; mySet1.add(o); mySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okay mySet1.has(1); // true mySet1.has(3); // false, since 3 has not been added to the set mySet1.has(5); // true mySet1.has(Math.sqrt(25)); // true mySet1.has("Some Text".toLowerCase()); // true mySet1.has(o); // true mySet1.size; // 5 mySet1.delete(5); // removes 5 from the set mySet1.has(5); // false, 5 has been removed mySet1.size; // 4, since we just removed one value mySet1.add(5); // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletion console.log(mySet1); // Set(5) { 1, "some text", {…}, {…}, 5 } ``` ### Iterating sets The iteration over a set visits elements in insertion order. ```js for (const item of mySet1) { console.log(item); } // 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5 for (const item of mySet1.keys()) { console.log(item); } // 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5 for (const item of mySet1.values()) { console.log(item); } // 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5 // key and value are the same here for (const [key, value] of mySet1.entries()) { console.log(key); } // 1, "some text", { "a": 1, "b": 2 }, { "a": 1, "b": 2 }, 5 // Convert Set object to an Array object, with Array.from const myArr = Array.from(mySet1); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}, 5] // the following will also work if run in an HTML document mySet1.add(document.body); mySet1.has(document.querySelector("body")); // true // converting between Set and Array const mySet2 = new Set([1, 2, 3, 4]); console.log(mySet2.size); // 4 console.log([...mySet2]); // [1, 2, 3, 4] // intersect can be simulated via const intersection = new Set([...mySet1].filter((x) => mySet2.has(x))); // difference can be simulated via const difference = new Set([...mySet1].filter((x) => !mySet2.has(x))); // Iterate set entries with forEach() mySet2.forEach((value) => { console.log(value); }); // 1 // 2 // 3 // 4 ``` ### Implementing basic set operations ```js function isSuperset(set, subset) { for (const elem of subset) { if (!set.has(elem)) { return false; } } return true; } function union(setA, setB) { const _union = new Set(setA); for (const elem of setB) { _union.add(elem); } return _union; } function intersection(setA, setB) { const _intersection = new Set(); for (const elem of setB) { if (setA.has(elem)) { _intersection.add(elem); } } return _intersection; } function symmetricDifference(setA, setB) { const _difference = new Set(setA); for (const elem of setB) { if (_difference.has(elem)) { _difference.delete(elem); } else { _difference.add(elem); } } return _difference; } function difference(setA, setB) { const _difference = new Set(setA); for (const elem of setB) { _difference.delete(elem); } return _difference; } // Examples const setA = new Set([1, 2, 3, 4]); const setB = new Set([2, 3]); const setC = new Set([3, 4, 5, 6]); isSuperset(setA, setB); // returns true union(setA, setC); // returns Set {1, 2, 3, 4, 5, 6} intersection(setA, setC); // returns Set {3, 4} symmetricDifference(setA, setC); // returns Set {1, 2, 5, 6} difference(setA, setC); // returns Set {1, 2} ``` ### Relation to arrays ```js const myArray = ["value1", "value2", "value3"]; // Use the regular Set constructor to transform an Array into a Set const mySet = new Set(myArray); mySet.has("value1"); // returns true // Use the spread syntax to transform a set into an Array. console.log([...mySet]); // Will show you exactly the same Array as myArray ``` ### Remove duplicate elements from an array ```js // Use to remove duplicate elements from an array const numbers = [2, 13, 4, 4, 2, 13, 13, 4, 4, 5, 5, 6, 6, 7, 5, 32, 13, 4, 5]; console.log([...new Set(numbers)]); // [2, 13, 4, 5, 6, 7, 32] ``` ### Relation to strings ```js // Case sensitive (set will contain "F" and "f") new Set("Firefox"); // Set(7) [ "F", "i", "r", "e", "f", "o", "x" ] // Duplicate omission ("f" occurs twice in the string but set will contain only one) new Set("firefox"); // Set(6) [ "f", "i", "r", "e", "o", "x" ] ``` ### Use a set to ensure the uniqueness of a list of values ```js const array = Array.from(document.querySelectorAll("[id]")).map((e) => e.id); const set = new Set(array); console.assert(set.size === array.length); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set` in `core-js`](https://github.com/zloirock/core-js#set) - {{jsxref("Map")}} - {{jsxref("WeakMap")}} - {{jsxref("WeakSet")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/intersection/index.md
--- title: Set.prototype.intersection() slug: Web/JavaScript/Reference/Global_Objects/Set/intersection page-type: javascript-instance-method browser-compat: javascript.builtins.Set.intersection --- {{JSRef}} The **`intersection()`** method of {{jsxref("Set")}} instances takes a set and returns a new set containing elements in both this set and the given set. ## Syntax ```js-nolint intersection(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value A new {{jsxref("Set")}} object containing elements in both this set and the `other` set. ## Description In mathematical notation, _intersection_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>∩</mo><mi>B</mi><mo>=</mo><mo stretchy="false">{</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mo>∣</mo><mi>x</mi><mo>∊</mo><mi>B</mi><mo stretchy="false">}</mo></mrow><annotation encoding="TeX">A\cap B = \{x\in A\mid x\in B\}</annotation></semantics></math> And using Venn diagram: ![A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap.](diagram.svg) `intersection()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, its behavior depends on the sizes of `this` and `other`: - If there are more elements in `this` than `other.size`, then it iterates over `other` by calling its `keys()` method, and constructs a new set with all elements produced that are also present in `this`. - Otherwise, it iterates over the elements in `this`, and constructs a new set with all elements `e` in `this` that cause `other.has(e)` to return a [truthy](/en-US/docs/Glossary/Truthy) value. Because of this implementation, the efficiency of `intersection()` mostly depends on the size of the smaller set between `this` and `other` (assuming sets can be accessed in sublinear time). The order of elements in the returned set is the same as that of the smaller of `this` and `other`. ## Examples ### Using intersection() The following example computes the intersection between the set of odd numbers (<10) and the set of perfect squares (<10). The result is the set of odd numbers that are perfect squares. ```js const odds = new Set([1, 3, 5, 7, 9]); const squares = new Set([1, 4, 9]); console.log(odds.intersection(squares)); // Set(2) { 1, 9 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.intersection` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/intersection/diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200" xml:space="preserve"><style>.st1{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><path d="M150 39.39c-20.92 12.1-35 34.71-35 60.61s14.08 48.51 35 60.61c20.92-12.1 35-34.71 35-60.61s-14.08-48.51-35-60.61z" style="fill:#39cac4"/><circle class="st1" cx="115" cy="100" r="70"/><circle class="st1" cx="185" cy="100" r="70"/><text transform="translate(99.37 50.4)">A</text><text transform="translate(190.014 50.4)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/add/index.md
--- title: Set.prototype.add() slug: Web/JavaScript/Reference/Global_Objects/Set/add page-type: javascript-instance-method browser-compat: javascript.builtins.Set.add --- {{JSRef}} The **`add()`** method of {{jsxref("Set")}} instances inserts a new element with a specified value in to this set, if there isn't an element with the same value already in this set {{EmbedInteractiveExample("pages/js/set-prototype-add.html")}} ## Syntax ```js-nolint add(value) ``` ### Parameters - `value` - : The value of the element to add to the `Set` object. ### Return value The `Set` object with added value. ## Examples ### Using the add() method ```js const mySet = new Set(); mySet.add(1); mySet.add(5).add("some text"); // chainable console.log(mySet); // Set [1, 5, "some text"] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Set.prototype.delete()")}} - {{jsxref("Set.prototype.has()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/has/index.md
--- title: Set.prototype.has() slug: Web/JavaScript/Reference/Global_Objects/Set/has page-type: javascript-instance-method browser-compat: javascript.builtins.Set.has --- {{JSRef}} The **`has()`** method of {{jsxref("Set")}} instances returns a boolean indicating whether an element with the specified value exists in this set or not. {{EmbedInteractiveExample("pages/js/set-prototype-has.html")}} ## Syntax ```js-nolint has(value) ``` ### Parameters - `value` - : The value to test for presence in the `Set` object. ### Return value Returns `true` if an element with the specified value exists in the `Set` object; otherwise `false`. ## Examples ### Using the has() method ```js const mySet = new Set(); mySet.add("foo"); console.log(mySet.has("foo")); // true console.log(mySet.has("bar")); // false const set1 = new Set(); const obj1 = { key1: 1 }; set1.add(obj1); console.log(set1.has(obj1)); // true console.log(set1.has({ key1: 1 })); // false, because they are different object references console.log(set1.add({ key1: 1 })); // now set1 contains 2 entries ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Set.prototype.add()")}} - {{jsxref("Set.prototype.delete()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/set/index.md
--- title: Set() constructor slug: Web/JavaScript/Reference/Global_Objects/Set/Set page-type: javascript-constructor browser-compat: javascript.builtins.Set.Set --- {{JSRef}} The **`Set()`** constructor creates {{jsxref("Set")}} objects. {{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}} ## Syntax ```js-nolint new Set() new Set(iterable) ``` > **Note:** `Set()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `iterable` {{optional_inline}} - : If an [iterable object](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `Set`. If you don't specify this parameter, or its value is `null`, the new `Set` is empty. ### Return value A new `Set` object. ## Examples ### Using the `Set` object ```js const mySet = new Set(); mySet.add(1); // Set [ 1 ] mySet.add(5); // Set [ 1, 5 ] mySet.add(5); // Set [ 1, 5 ] mySet.add("some text"); // Set [ 1, 5, 'some text' ] const o = { a: 1, b: 2 }; mySet.add(o); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set` in `core-js`](https://github.com/zloirock/core-js#set) - {{jsxref("Set")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/keys/index.md
--- title: Set.prototype.keys() slug: Web/JavaScript/Reference/Global_Objects/Set/keys page-type: javascript-instance-method browser-compat: javascript.builtins.Set.keys --- {{JSRef}} The **`keys()`** method of {{jsxref("Set")}} instances is an alias for the [`values()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values) method. ## Syntax ```js-nolint keys() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Examples ### Using keys() The `keys()` method is exactly equivalent to the {{jsxref("Set/values", "values()")}} method. ```js const mySet = new Set(); mySet.add("foo"); mySet.add("bar"); mySet.add("baz"); const setIter = mySet.keys(); console.log(setIter.next().value); // "foo" console.log(setIter.next().value); // "bar" console.log(setIter.next().value); // "baz" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set.prototype.entries()")}} - {{jsxref("Set.prototype.values()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/clear/index.md
--- title: Set.prototype.clear() slug: Web/JavaScript/Reference/Global_Objects/Set/clear page-type: javascript-instance-method browser-compat: javascript.builtins.Set.clear --- {{JSRef}} The **`clear()`** method of {{jsxref("Set")}} instances removes all elements from this set. {{EmbedInteractiveExample("pages/js/set-prototype-clear.html")}} ## Syntax ```js-nolint clear() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Using the clear() method ```js const mySet = new Set(); mySet.add(1); mySet.add("foo"); console.log(mySet.size); // 2 console.log(mySet.has("foo")); // true mySet.clear(); console.log(mySet.size); // 0 console.log(mySet.has("foo")); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Set.prototype.delete()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/issubsetof/index.md
--- title: Set.prototype.isSubsetOf() slug: Web/JavaScript/Reference/Global_Objects/Set/isSubsetOf page-type: javascript-instance-method browser-compat: javascript.builtins.Set.isSubsetOf --- {{JSRef}} The **`isSubsetOf()`** method of {{jsxref("Set")}} instances takes a set and returns a boolean indicating if all elements of this set are in the given set. ## Syntax ```js-nolint isSubsetOf(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value `true` if all elements in this set are also in the `other` set, and `false` otherwise. ## Description In mathematical notation, _subset_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>⊆</mo><mi>B</mi><mo stretchy="false">⇔</mo><mo>∀</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mo>,</mo><mspace width="0.16666666666666666em"></mspace><mi>x</mi><mo>∊</mo><mi>B</mi></mrow><annotation encoding="TeX">A\subseteq B \Leftrightarrow \forall x\in A,\,x\in B</annotation></semantics></math> And using Venn diagram: ![A Venn diragram with two circles. A is a subset of B because A is completely contained in B.](diagram.svg) > **Note:** The _subset_ relationship is not _proper subset_, which means `isSubsetOf()` returns `true` if `this` and `other` contain the same elements. `isSubsetOf()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, its behavior depends on the sizes of `this` and `other`: - If there are more elements in `this` than `other.size`, then it directly returns `false`. - Otherwise, it iterates over the elements in `this`, and returns `false` if any element `e` in `this` causes `other.has(e)` to return a [falsy](/en-US/docs/Glossary/Falsy) value. Otherwise, it returns `true`. ## Examples ### Using isSubsetOf() The set of multiples of 4 (<20) is a subset of even numbers (<20): ```js const fours = new Set([4, 8, 12, 16]); const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]); console.log(fours.isSubsetOf(evens)); // true ``` The set of prime numbers (<20) is not a subset of all odd numbers (<20), because 2 is prime but not odd: ```js const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]); const odds = new Set([3, 5, 7, 9, 11, 13, 15, 17, 19]); console.log(primes.isSubsetOf(odds)); // false ``` Equivalent sets are subsets of each other: ```js const set1 = new Set([1, 2, 3]); const set2 = new Set([1, 2, 3]); console.log(set1.isSubsetOf(set2)); // true console.log(set2.isSubsetOf(set1)); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.isSubsetOf` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/issubsetof/diagram.svg
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 300 200" xml:space="preserve"><style>.st0{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><circle class="st0" cx="150" cy="100" r="75"/><circle class="st0" cx="150" cy="120" r="50"/><text transform="translate(144.361 94.51)">A</text><text transform="translate(144.358 44.51)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/union/index.md
--- title: Set.prototype.union() slug: Web/JavaScript/Reference/Global_Objects/Set/union page-type: javascript-instance-method browser-compat: javascript.builtins.Set.union --- {{JSRef}} The **`union()`** method of {{jsxref("Set")}} instances takes a set and returns a new set containing elements which are in either or both of this set and the given set. ## Syntax ```js-nolint union(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value A new {{jsxref("Set")}} object containing elements which are in either or both of this set and the `other` set. ## Description In mathematical notation, _union_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>∪</mo><mi>B</mi><mo>=</mo><mo stretchy="false">{</mo><mi>x</mi><mo>∣</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mtext>&nbsp;or&nbsp;</mtext><mi>x</mi><mo>∊</mo><mi>B</mi><mo stretchy="false">}</mo></mrow><annotation encoding="TeX">A\cup B = \{x\midx\in A\text{ or }x\in B\}</annotation></semantics></math> And using Venn diagram: ![A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either or both circles.](diagram.svg) `union()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, it iterates over `other` by calling its `keys()` method, and constructs a new set with all elements in `this`, followed by all elements in `other` that are not present in `this`. The order of elements in the returned set is first those in `this` followed by those in `other`. ## Examples ### Using union() The following example computes the union between the set of even numbers (<10) and the set of perfect squares (<10). The result is the set of numbers that are either even or a perfect square, or both. ```js const evens = new Set([2, 4, 6, 8]); const squares = new Set([1, 4, 9]); console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.union` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/union/diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200" xml:space="preserve"><style>.st1{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><path d="M185 30c-12.75 0-24.7 3.43-35 9.39A69.667 69.667 0 0 0 115 30c-38.66 0-70 31.34-70 70s31.34 70 70 70c12.75 0 24.7-3.43 35-9.39a69.667 69.667 0 0 0 35 9.39c38.66 0 70-31.34 70-70s-31.34-70-70-70z" style="fill:#39cac4"/><circle class="st1" cx="115" cy="100" r="70"/><circle class="st1" cx="185" cy="100" r="70"/><text transform="translate(99.37 50.4)">A</text><text transform="translate(190.014 50.4)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/issupersetof/index.md
--- title: Set.prototype.isSupersetOf() slug: Web/JavaScript/Reference/Global_Objects/Set/isSupersetOf page-type: javascript-instance-method browser-compat: javascript.builtins.Set.isSupersetOf --- {{JSRef}} The **`isSupersetOf()`** method of {{jsxref("Set")}} instances takes a set and returns a boolean indicating if all elements of the given set are in this set. ## Syntax ```js-nolint isSupersetOf(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value `true` if all elements in the `other` set are also in this set, and `false` otherwise. ## Description In mathematical notation, _superset_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>⊇</mo><mi>B</mi><mo stretchy="false">⇔</mo><mo>∀</mo><mi>x</mi><mo>∊</mo><mi>B</mi><mo>,</mo><mspace width="0.16666666666666666em"></mspace><mi>x</mi><mo>∊</mo><mi>A</mi></mrow><annotation encoding="TeX">A\supseteq B \Leftrightarrow \forall x\in B,\,x\in A</annotation></semantics></math> And using Venn diagram: ![A Venn diagram with two circles. A is a superset of B because B is completely contained in A.](diagram.svg) > **Note:** The _superset_ relationship is not _proper superset_, which means `isSupersetOf()` returns `true` if `this` and `other` contain the same elements. `isSupersetOf()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, its behavior depends on the sizes of `this` and `other`: - If there are fewer elements in `this` than `other.size`, then it directly returns `false`. - Otherwise, it iterates over `other` by calling its `keys()` method, and if any element in `other` is not present in `this`, it returns `false` (and closes the `keys()` iterator by calling its `return()` method). Otherwise, it returns `true`. ## Examples ### Using isSupersetOf() The set of even numbers (<20) is a superset of multiples of 4 (<20): ```js const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]); const fours = new Set([4, 8, 12, 16]); console.log(evens.isSupersetOf(fours)); // true ``` The set of all odd numbers (<20) is not a superset of prime numbers (<20), because 2 is prime but not odd: ```js const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]); const odds = new Set([3, 5, 7, 9, 11, 13, 15, 17, 19]); console.log(odds.isSupersetOf(primes)); // false ``` Equivalent sets are supersets of each other: ```js const set1 = new Set([1, 2, 3]); const set2 = new Set([1, 2, 3]); console.log(set1.isSupersetOf(set2)); // true console.log(set2.isSupersetOf(set1)); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.isSupersetOf` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/issupersetof/diagram.svg
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 300 200" xml:space="preserve"><style>.st0{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><circle class="st0" cx="150" cy="100" r="75"/><circle class="st0" cx="150" cy="120" r="50"/><text transform="translate(144.358 44.51)">A</text><text transform="translate(144.361 94.51)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/size/index.md
--- title: Set.prototype.size slug: Web/JavaScript/Reference/Global_Objects/Set/size page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.Set.size --- {{JSRef}} The **`size`** accessor property of {{jsxref("Set")}} instances returns the number of (unique) elements in this set. {{EmbedInteractiveExample("pages/js/set-prototype-size.html")}} ## Description The value of `size` is an integer representing how many entries the `Set` object has. A set accessor function for `size` is `undefined`; you cannot change this property. ## Examples ### Using size ```js const mySet = new Set(); mySet.add(1); mySet.add(5); mySet.add("some text"); console.log(mySet.size); // 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/values/index.md
--- title: Set.prototype.values() slug: Web/JavaScript/Reference/Global_Objects/Set/values page-type: javascript-instance-method browser-compat: javascript.builtins.Set.values --- {{JSRef}} The **`values()`** method of {{jsxref("Set")}} instances returns a new _[set iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the values for each element in this set in insertion order. {{EmbedInteractiveExample("pages/js/set-prototype-values.html")}} ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Examples ### Using values() ```js const mySet = new Set(); mySet.add("foo"); mySet.add("bar"); mySet.add("baz"); const setIter = mySet.values(); console.log(setIter.next().value); // "foo" console.log(setIter.next().value); // "bar" console.log(setIter.next().value); // "baz" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set.prototype.entries()")}} - {{jsxref("Set.prototype.keys()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/symmetricdifference/index.md
--- title: Set.prototype.symmetricDifference() slug: Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference page-type: javascript-instance-method browser-compat: javascript.builtins.Set.symmetricDifference --- {{JSRef}} The **`symmetricDifference()`** method of {{jsxref("Set")}} instances takes a set and returns a new set containing elements which are in either this set or the given set, but not in both. ## Syntax ```js-nolint symmetricDifference(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value A new {{jsxref("Set")}} object containing elements which are in either this set or the `other` set, but not in both. ## Description In mathematical notation, _symmetric difference_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>⊖</mo><mi>B</mi><mo>=</mo><mo stretchy="false">(</mo><mi>A</mi><mo>∖</mo><mi>B</mi><mo stretchy="false">)</mo><mo>∪</mo><mo stretchy="false">(</mo><mi>B</mi><mo>∖</mo><mi>A</mi><mo stretchy="false">)</mo></mrow><annotation encoding="TeX">A\ominus B = (A\setminus B)\cup(B\setminus A)</annotation></semantics></math> And using Venn diagram: ![A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either circle but not both.](diagram.svg) `symmetricDifference()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, it iterates over `other` by calling its `keys()` method, and constructs a new set with all elements in `this` that are not seen in `other`, and all elements in `other` that are not seen in `this`. The order of elements in the returned set is first those in `this` followed by those in `other`. ## Examples ### Using symmetricDifference() The following example computes the symmetric difference between the set of even numbers (<10) and the set of perfect squares (<10). The result is the set of numbers that are either even or a perfect square, but not both. ```js const evens = new Set([2, 4, 6, 8]); const squares = new Set([1, 4, 9]); console.log(evens.symmetricDifference(squares)); // Set(5) { 1, 2, 6, 8, 9 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.symmetricDifference` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/symmetricdifference/diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200" xml:space="preserve"><style>.st1{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><path d="M115 100c0-25.91 14.08-48.51 35-60.61A69.667 69.667 0 0 0 115 30c-38.66 0-70 31.34-70 70s31.34 70 70 70c12.75 0 24.7-3.43 35-9.39-20.92-12.1-35-34.7-35-60.61zm70-70c-12.75 0-24.7 3.43-35 9.39 20.92 12.1 35 34.71 35 60.61s-14.08 48.51-35 60.61a69.667 69.667 0 0 0 35 9.39c38.66 0 70-31.34 70-70s-31.34-70-70-70z" style="fill:#39cac4"/><circle class="st1" cx="115" cy="100" r="70"/><circle class="st1" cx="185" cy="100" r="70"/><text transform="translate(99.37 50.4)">A</text><text transform="translate(190.014 50.4)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/@@iterator/index.md
--- title: Set.prototype[@@iterator]() slug: Web/JavaScript/Reference/Global_Objects/Set/@@iterator page-type: javascript-instance-method browser-compat: javascript.builtins.Set.@@iterator --- {{JSRef}} The **`[@@iterator]()`** method of {{jsxref("Set")}} instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows `Set` objects to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns a [set iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the values of the set in insertion order. The initial value of this property is the same function object as the initial value of the {{jsxref("Set.prototype.values")}} property. {{EmbedInteractiveExample("pages/js/set-prototype-@@iterator.html")}} ## Syntax ```js-nolint set[Symbol.iterator]() ``` ### Parameters None. ### Return value The same return value as {{jsxref("Set.prototype.values()")}}: a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the values of the set. ## Examples ### Iteration using for...of loop Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Set` objects [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over. ```js const mySet = new Set(); mySet.add("0"); mySet.add(1); mySet.add({}); for (const v of mySet) { console.log(v); } ``` ### Manually hand-rolling the iterator You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process. ```js const mySet = new Set(); mySet.add("0"); mySet.add(1); mySet.add({}); const setIter = mySet[Symbol.iterator](); console.log(setIter.next().value); // "0" console.log(setIter.next().value); // 1 console.log(setIter.next().value); // {} ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Set.prototype.entries()")}} - {{jsxref("Set.prototype.keys()")}} - {{jsxref("Set.prototype.values()")}} - {{jsxref("Symbol.iterator")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/delete/index.md
--- title: Set.prototype.delete() slug: Web/JavaScript/Reference/Global_Objects/Set/delete page-type: javascript-instance-method browser-compat: javascript.builtins.Set.delete --- {{JSRef}} The **`delete()`** method of {{jsxref("Set")}} instances removes a specified value from this set, if it is in the set. {{EmbedInteractiveExample("pages/js/set-prototype-delete.html")}} ## Syntax ```js-nolint setInstance.delete(value) ``` ### Parameters - `value` - : The value to remove from `Set`. ### Return value Returns `true` if `value` was already in `Set`; otherwise `false`. ## Examples ### Using the delete() method ```js const mySet = new Set(); mySet.add("foo"); console.log(mySet.delete("bar")); // false; no "bar" element found to be deleted. console.log(mySet.delete("foo")); // true; successfully removed. console.log(mySet.has("foo")); // false; the "foo" element is no longer present. ``` ### Deleting an object from a set Because objects are compared by reference, you have to delete them by checking individual properties if you don't have a reference to the original object. ```js const setObj = new Set(); // Create a new set. setObj.add({ x: 10, y: 20 }); // Add object in the set. setObj.add({ x: 20, y: 30 }); // Add object in the set. // Delete any point with `x > 10`. setObj.forEach((point) => { if (point.x > 10) { setObj.delete(point); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Set.prototype.clear()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/foreach/index.md
--- title: Set.prototype.forEach() slug: Web/JavaScript/Reference/Global_Objects/Set/forEach page-type: javascript-instance-method browser-compat: javascript.builtins.Set.forEach --- {{JSRef}} The **`forEach()`** method of {{jsxref("Set")}} instances executes a provided function once for each value in this set, in insertion order. {{EmbedInteractiveExample("pages/js/set-prototype-foreach.html")}} ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callback` - : A function to execute for each entry in the set. The function is called with the following arguments: - `value` - : Value of each iteration. - `key` - : Key of each iteration. This is always the same as `value`. - `set` - : The set being iterated. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. ### Return value None ({{jsxref("undefined")}}). ## Description The `forEach()` method executes the provided `callback` once for each value which actually exists in the `Set` object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value `undefined`. `callback` is invoked with **three arguments**: - the **element value** - the **element key** - the **`Set` object being traversed** There are no keys in `Set` objects, however, so the first two arguments are both **values** contained in the {{jsxref("Set")}}. This is to make it consistent with other `forEach()` methods for {{jsxref("Map/foreach", "Map")}} and {{jsxref("Array/forEach", "Array")}}. If a `thisArg` parameter is provided to `forEach()`, it will be passed to `callback` when invoked, for use as its `this` value. Otherwise, the value `undefined` will be passed for use as its `this` value. The `this` value ultimately observable by `callback` is determined according to [the usual rules for determining the `this` seen by a function](/en-US/docs/Web/JavaScript/Reference/Operators/this). Each value is visited once, except in the case when it was deleted and re-added before `forEach()` has finished. `callback` is not invoked for values deleted before being visited. New values added before `forEach()` has finished will be visited. `forEach()` executes the `callback` function once for each element in the `Set` object; it does not return a value. ## Examples ### Logging the contents of a Set object The following code logs a line for each element in a `Set` object: ```js function logSetElements(value1, value2, set) { console.log(`s[${value1}] = ${value2}`); } new Set(["foo", "bar", undefined]).forEach(logSetElements); // Logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Array.prototype.forEach()")}} - {{jsxref("Map.prototype.forEach()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/isdisjointfrom/index.md
--- title: Set.prototype.isDisjointFrom() slug: Web/JavaScript/Reference/Global_Objects/Set/isDisjointFrom page-type: javascript-instance-method browser-compat: javascript.builtins.Set.isDisjointFrom --- {{JSRef}} The **`isDisjointFrom()`** method of {{jsxref("Set")}} instances takes a set and returns a boolean indicating if this set has no elements in common with the given set. ## Syntax ```js-nolint isDisjointFrom(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value `true` if this set has no elements in common with the `other` set, and `false` otherwise. ## Description Two sets are _disjoint_ if they have no elements in common. In mathematical notation: <math display="block"><semantics><mrow><mi>A</mi><mtext>&nbsp;is disjoint from&nbsp;</mtext><mi>B</mi><mo stretchy="false">⇔</mo><mi>A</mi><mo>∩</mo><mi>B</mi><mo>=</mo><mi>∅</mi></mrow><annotation encoding="TeX">A\text{ is disjoint from }B \Leftrightarrow A\cap B = \empty</annotation></semantics></math> And using Venn diagram: ![A Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap.](diagram.svg) `isDisjointFrom()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, its behavior depends on the sizes of `this` and `other`: - If there are more elements in `this` than `other.size`, then it iterates over `other` by calling its `keys()` method, and if any element in `other` is present in `this`, it returns `false` (and closes the `keys()` iterator by calling its `return()` method). Otherwise, it returns `true`. - Otherwise, it iterates over the elements in `this`, and returns `false` if any element `e` in `this` causes `other.has(e)` to return a [truthy](/en-US/docs/Glossary/Truthy) value. Otherwise, it returns `true`. Because of this implementation, the efficiency of `isDisjointFrom()` mostly depends on the size of the smaller set between `this` and `other` (assuming sets can be accessed in sublinear time). ## Examples ### Using isDisjointFrom() The set of perfect squares (<20) is disjoint from the set of prime numbers (<20), because a perfect square is by definition decomposable into the product of two integers, while 1 is also not considered a prime number: ```js const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]); const squares = new Set([1, 4, 9, 16]); console.log(primes.isDisjointFrom(squares)); // true ``` The set of perfect squares (<20) is not disjoint from the set of composite numbers (<20), because all non-1 perfect squares are by definition composite numbers: ```js const composites = new Set([4, 6, 8, 9, 10, 12, 14, 15, 16, 18]); const squares = new Set([1, 4, 9, 16]); console.log(composites.isDisjointFrom(squares)); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.isDisjointFrom` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.difference()")}} - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/isdisjointfrom/diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200" xml:space="preserve"><style>.st0{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><circle class="st0" cx="90" cy="100" r="50"/><circle class="st0" cx="210" cy="100" r="50"/><text transform="translate(85.996 63.2)">A</text><text transform="translate(205.998 63.2)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/@@species/index.md
--- title: Set[@@species] slug: Web/JavaScript/Reference/Global_Objects/Set/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.Set.@@species --- {{JSRef}} The **`Set[@@species]`** static accessor property is an unused accessor property specifying how to copy `Set` objects. ## Syntax ```js-nolint Set[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `Set` instances. ## Description The `@@species` accessor property returns the default constructor for `Set` objects. Subclass constructors may override it to change the constructor assignment. > **Note:** This property is currently unused by all `Set` methods. ## Examples ### Species in ordinary objects The `@@species` property returns the default constructor function, which is the `Set` constructor for `Set`. ```js Set[Symbol.species]; // function Set() ``` ### Species in derived objects In an instance of a custom `Set` subclass, such as `MySet`, the `MySet` species is the `MySet` constructor. However, you might want to overwrite this, in order to return parent `Set` objects in your derived class methods: ```js class MySet extends Set { // Overwrite MySet species to the parent Set constructor static get [Symbol.species]() { return Set; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/difference/index.md
--- title: Set.prototype.difference() slug: Web/JavaScript/Reference/Global_Objects/Set/difference page-type: javascript-instance-method browser-compat: javascript.builtins.Set.difference --- {{JSRef}} The **`difference()`** method of {{jsxref("Set")}} instances takes a set and returns a new set containing elements in this set but not in the given set. ## Syntax ```js-nolint difference(other) ``` ### Parameters - `other` - : A {{jsxref("Set")}} object, or [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) object. ### Return value A new {{jsxref("Set")}} object containing elements in this set but not in the `other` set. ## Description In mathematical notation, _difference_ is defined as: <math display="block"><semantics><mrow><mi>A</mi><mo>∖</mo><mi>B</mi><mo>=</mo><mo stretchy="false">{</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mo>∣</mo><mi>x</mi><mo>∉</mo><mi>B</mi><mo stretchy="false">}</mo></mrow><annotation encoding="TeX">A\setminus B = \{x\in A\mid x\notin B\}</annotation></semantics></math> And using Venn diagram: ![A Venn diagram where two circles overlap. The difference of A and B is the part of A that is not overlapping B.](diagram.svg) `difference()` accepts [set-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects) objects as the `other` parameter. It requires {{jsxref("Operators/this", "this")}} to be an actual {{jsxref("Set")}} instance, because it directly retrieves the underlying data stored in `this` without invoking any user code. Then, its behavior depends on the sizes of `this` and `other`: - If there are more elements in `this` than `other.size`, then it iterates over `other` by calling its `keys()` method, and constructs a new set with all elements in `this` that are not seen in `other`. - Otherwise, it iterates over the elements in `this`, and constructs a new set with all elements `e` in `this` that cause `other.has(e)` to return a [falsy](/en-US/docs/Glossary/Falsy) value. The order of elements in the returned set is the same as in `this`. ## Examples ### Using difference() The following example computes the difference between the set of odd numbers (<10) and the set of perfect squares (<10). The result is the set of odd numbers that are not perfect squares. ```js const odds = new Set([1, 3, 5, 7, 9]); const squares = new Set([1, 4, 9]); console.log(odds.difference(squares)); // Set(3) { 3, 5, 7 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Set.prototype.difference` in `core-js`](https://github.com/zloirock/core-js#new-set-methods) - {{jsxref("Set.prototype.intersection()")}} - {{jsxref("Set.prototype.isDisjointFrom()")}} - {{jsxref("Set.prototype.isSubsetOf()")}} - {{jsxref("Set.prototype.isSupersetOf()")}} - {{jsxref("Set.prototype.symmetricDifference()")}} - {{jsxref("Set.prototype.union()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/difference/diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200" xml:space="preserve"><style>.st1{fill:none;stroke:#231f20;stroke-miterlimit:10}</style><path d="M115 100c0-25.91 14.08-48.51 35-60.61A69.667 69.667 0 0 0 115 30c-38.66 0-70 31.34-70 70s31.34 70 70 70c12.75 0 24.7-3.43 35-9.39-20.92-12.1-35-34.7-35-60.61z" style="fill:#39cac4"/><circle class="st1" cx="115" cy="100" r="70"/><circle class="st1" cx="185" cy="100" r="70"/><text transform="translate(99.37 50.4)">A</text><text transform="translate(190.014 50.4)">B</text></svg>
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set
data/mdn-content/files/en-us/web/javascript/reference/global_objects/set/entries/index.md
--- title: Set.prototype.entries() slug: Web/JavaScript/Reference/Global_Objects/Set/entries page-type: javascript-instance-method browser-compat: javascript.builtins.Set.entries --- {{JSRef}} The **`entries()`** method of {{jsxref("Set")}} instances returns a new _[set iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains **an array of `[value, value]`** for each element in this set, in insertion order. For `Set` objects there is no `key` like in `Map` objects. However, to keep the API similar to the `Map` object, each _entry_ has the same value for its _key_ and _value_ here, so that an array `[value, value]` is returned. {{EmbedInteractiveExample("pages/js/set-prototype-entries.html")}} ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Examples ### Using entries() ```js const mySet = new Set(); mySet.add("foobar"); mySet.add(1); mySet.add("baz"); const setIter = mySet.entries(); console.log(setIter.next().value); // ["foobar", "foobar"] console.log(setIter.next().value); // [1, 1] console.log(setIter.next().value); // ["baz", "baz"] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Set.prototype.keys()")}} - {{jsxref("Set.prototype.values()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/infinity/index.md
--- title: Infinity slug: Web/JavaScript/Reference/Global_Objects/Infinity page-type: javascript-global-property browser-compat: javascript.builtins.Infinity --- {{jsSidebar("Objects")}} The **`Infinity`** global property is a numeric value representing infinity. {{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}} ## Value The same number value as {{jsxref("Number.POSITIVE_INFINITY")}}. {{js_property_attributes(0, 0, 0)}} ## Description `Infinity` is a property of the _global object_. In other words, it is a variable in global scope. The value `Infinity` (positive infinity) is greater than any other number. This value behaves slightly differently than mathematical infinity; see {{jsxref("Number.POSITIVE_INFINITY")}} for details. ## Examples ### Using Infinity ```js console.log(Infinity); /* Infinity */ console.log(Infinity + 1); /* Infinity */ console.log(Math.pow(10, 1000)); /* Infinity */ console.log(Math.log(0)); /* -Infinity */ console.log(1 / Infinity); /* 0 */ console.log(1 / 0); /* Infinity */ ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.NEGATIVE_INFINITY")}} - {{jsxref("Number.POSITIVE_INFINITY")}} - {{jsxref("Number.isFinite")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/biguint64array/index.md
--- title: BigUint64Array slug: Web/JavaScript/Reference/Global_Objects/BigUint64Array page-type: javascript-class browser-compat: javascript.builtins.BigUint64Array --- {{JSRef}} The **`BigUint64Array`** typed array represents an array of 64-bit unsigned integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0n`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). `BigUint64Array` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("BigUint64Array/BigUint64Array", "BigUint64Array()")}} - : Creates a new `BigUint64Array` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "BigUint64Array.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `8` in the case of `BigUint64Array`. ## Static methods _Inherits static methods from its parent {{jsxref("TypedArray")}}_. ## Instance properties _Also inherits instance properties from its parent {{jsxref("TypedArray")}}_. These properties are defined on `BigUint64Array.prototype` and shared by all `BigUint64Array` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "BigUint64Array.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `8` in the case of a `BigUint64Array`. - {{jsxref("Object/constructor", "BigUint64Array.prototype.constructor")}} - : The constructor function that created the instance object. For `BigUint64Array` instances, the initial value is the {{jsxref("BigUint64Array/BigUint64Array", "BigUint64Array")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("TypedArray")}}_. ## Examples ### Different ways to create a BigUint64Array ```js // From a length const biguint64 = new BigUint64Array(2); biguint64[0] = 42n; console.log(biguint64[0]); // 42n console.log(biguint64.length); // 2 console.log(biguint64.BYTES_PER_ELEMENT); // 8 // From an array const x = new BigUint64Array([21n, 31n]); console.log(x[1]); // 31n // From another TypedArray const y = new BigUint64Array(x); console.log(y[0]); // 21n // From an ArrayBuffer const buffer = new ArrayBuffer(64); const z = new BigUint64Array(buffer, 8, 4); console.log(z.byteOffset); // 8 // From an iterable const iterable = (function* () { yield* [1n, 2n, 3n]; })(); const biguint64FromIterable = new BigUint64Array(iterable); console.log(biguint64FromIterable); // BigUint64Array [1n, 2n, 3n] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/biguint64array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/biguint64array/biguint64array/index.md
--- title: BigUint64Array() constructor slug: Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array page-type: javascript-constructor browser-compat: javascript.builtins.BigUint64Array.BigUint64Array --- {{JSRef}} The **`BigUint64Array()`** constructor creates {{jsxref("BigUint64Array")}} objects. The contents are initialized to `0n`. ## Syntax ```js-nolint new BigUint64Array() new BigUint64Array(length) new BigUint64Array(typedArray) new BigUint64Array(object) new BigUint64Array(buffer) new BigUint64Array(buffer, byteOffset) new BigUint64Array(buffer, byteOffset, length) ``` > **Note:** `BigUint64Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ## Examples ### Different ways to create a BigUint64Array ```js // From a length const biguint64 = new BigUint64Array(2); biguint64[0] = 42n; console.log(biguint64[0]); // 42n console.log(biguint64.length); // 2 console.log(biguint64.BYTES_PER_ELEMENT); // 8 // From an array const x = new BigUint64Array([21n, 31n]); console.log(x[1]); // 31n // From another TypedArray const y = new BigUint64Array(x); console.log(y[0]); // 21n // From an ArrayBuffer const buffer = new ArrayBuffer(64); const z = new BigUint64Array(buffer, 8, 4); console.log(z.byteOffset); // 8 // From an iterable const iterable = (function* () { yield* [1n, 2n, 3n]; })(); const biguint64FromIterable = new BigUint64Array(iterable); console.log(biguint64FromIterable); // BigUint64Array [1n, 2n, 3n] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/index.md
--- title: ArrayBuffer slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer page-type: javascript-class browser-compat: javascript.builtins.ArrayBuffer --- {{JSRef}} The **`ArrayBuffer`** object is used to represent a generic raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array". You cannot directly manipulate the contents of an `ArrayBuffer`; instead, you create one of the [typed array objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a {{jsxref("DataView")}} object which represents the buffer in a specific format, and use that to read and write the contents of the buffer. The [`ArrayBuffer()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer) constructor creates a new `ArrayBuffer` of the given length in bytes. You can also get an array buffer from existing data, for example, from a [Base64](/en-US/docs/Glossary/Base64) string or [from a local file](/en-US/docs/Web/API/FileReader/readAsArrayBuffer). `ArrayBuffer` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects). ## Description ### Resizing ArrayBuffers `ArrayBuffer` objects can be made resizable by including the `maxByteLength` option when calling the {{jsxref("ArrayBuffer/ArrayBuffer", "ArrayBuffer()")}} constructor. You can query whether an `ArrayBuffer` is resizable and what its maximum size is by accessing its {{jsxref("ArrayBuffer/resizable", "resizable")}} and {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} properties, respectively. You can assign a new size to a resizable `ArrayBuffer` with a {{jsxref("ArrayBuffer/resize", "resize()")}} call. New bytes are initialized to 0. These features make resizing `ArrayBuffer`s more efficient — otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with [`WebAssembly.Memory.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow)). ### Transferring ArrayBuffers `ArrayBuffer` objects can be transferred between different execution contexts, like [Web Workers](/en-US/docs/Web/API/Web_Workers_API) or [Service Workers](/en-US/docs/Web/API/Service_Worker_API), using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This is done by passing the `ArrayBuffer` as a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in a call to {{domxref("Worker.postMessage()")}} or {{domxref("ServiceWorker.postMessage()")}}. In pure JavaScript, you can also transfer the ownership of memory from one `ArrayBuffer` to another using its {{jsxref("ArrayBuffer/transfer", "transfer()")}} or {{jsxref("ArrayBuffer/transferToFixedLength", "transferToFixedLength()")}} method. When an `ArrayBuffer` is transferred, its original copy becomes _detached_ — this means it is no longer usable. At any moment, there will only be one copy of the `ArrayBuffer` that actually has access to the underlying memory. Detached buffers have the following behaviors: - {{jsxref("ArrayBuffer/byteLength", "byteLength")}} becomes 0 (in both the buffer and the associated typed array views). - Methods, such as {{jsxref("ArrayBuffer/resize", "resize()")}} and {{jsxref("ArrayBuffer/slice", "slice()")}}, throw a {{jsxref("TypeError")}} when invoked. The associated typed array views' methods also throw a `TypeError`. You can check whether an `ArrayBuffer` is detached by its {{jsxref("ArrayBuffer/detached", "detached")}} property. ## Constructor - {{jsxref("ArrayBuffer/ArrayBuffer", "ArrayBuffer()")}} - : Creates a new `ArrayBuffer` object. ## Static properties - {{jsxref("ArrayBuffer/@@species", "ArrayBuffer[@@species]")}} - : The constructor function that is used to create derived objects. ## Static methods - {{jsxref("ArrayBuffer.isView()")}} - : Returns `true` if `arg` is one of the ArrayBuffer views, such as [typed array objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a {{jsxref("DataView")}}. Returns `false` otherwise. ## Instance properties These properties are defined on `ArrayBuffer.prototype` and shared by all `ArrayBuffer` instances. - {{jsxref("ArrayBuffer.prototype.byteLength")}} - : The size, in bytes, of the `ArrayBuffer`. This is established when the array is constructed and can only be changed using the {{jsxref("ArrayBuffer.prototype.resize()")}} method if the `ArrayBuffer` is resizable. - {{jsxref("Object/constructor", "ArrayBuffer.prototype.constructor")}} - : The constructor function that created the instance object. For `ArrayBuffer` instances, the initial value is the {{jsxref("ArrayBuffer/ArrayBuffer", "ArrayBuffer")}} constructor. - {{jsxref("ArrayBuffer.prototype.detached")}} - : Read-only. Returns `true` if the `ArrayBuffer` has been detached (transferred), or `false` if not. - {{jsxref("ArrayBuffer.prototype.maxByteLength")}} - : The read-only maximum length, in bytes, that the `ArrayBuffer` can be resized to. This is established when the array is constructed and cannot be changed. - {{jsxref("ArrayBuffer.prototype.resizable")}} - : Read-only. Returns `true` if the `ArrayBuffer` can be resized, or `false` if not. - `ArrayBuffer.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"ArrayBuffer"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("ArrayBuffer.prototype.resize()")}} - : Resizes the `ArrayBuffer` to the specified size, in bytes. - {{jsxref("ArrayBuffer.prototype.slice()")}} - : Returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin` (inclusive) up to `end` (exclusive). If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. - {{jsxref("ArrayBuffer.prototype.transfer()")}} - : Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. - {{jsxref("ArrayBuffer.prototype.transferToFixedLength()")}} - : Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. ## Examples ### Creating an ArrayBuffer In this example, we create a 8-byte buffer with a {{jsxref("Int32Array")}} view referring to the buffer: ```js const buffer = new ArrayBuffer(8); const view = new Int32Array(buffer); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `ArrayBuffer` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("SharedArrayBuffer")}} - [RangeError: invalid array length](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/resizable/index.md
--- title: ArrayBuffer.prototype.resizable slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resizable page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.ArrayBuffer.resizable --- {{JSRef}} The **`resizable`** accessor property of {{jsxref("ArrayBuffer")}} instances returns whether this array buffer can be resized or not. {{EmbedInteractiveExample("pages/js/arraybuffer-resizable.html")}} ## Description The `resizable` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed. If the `maxByteLength` option was set in the constructor, `resizable` will return `true`; if not, it will return `false`. ## Examples ### Using resizable In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its `resizable` property, resizing it if `resizable` returns `true`: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); if (buffer.resizable) { console.log("Buffer is resizable!"); buffer.resize(12); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.maxByteLength")}} - {{jsxref("ArrayBuffer.prototype.resize()")}}
0