Set.prototype.delete() - JavaScript

Set.prototype.delete()
======================

The **`delete()`** method of `Set` instances removes a specified value from this set, if it is in the set.

Try it
------

Syntax
------

```js
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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.delete |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`
* `Set.prototype.clear()`


Set.prototype.union() - JavaScript

Set.prototype.union()
=====================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`union()`** method of `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
union(other)
```

### Parameters

`other`

A `Set` object, or set-like object.

### Return value

A new `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:

A
∪
B
=
{
x
∣
x
∊
A
 or
x
∊
B
}

A\cup B = {x\midx\in A\text{ or }x\in B}

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.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/union/diagram.svg)

`union()` accepts set-like objects as the `other` parameter. It requires `this` to be an actual `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) { 1, 2, 4, 6, 8, 9 }
```

Specifications
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.union |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.union` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.intersection()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.symmetricDifference()`


Set.prototype.isDisjointFrom() - JavaScript

Set.prototype.isDisjointFrom()
==============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`isDisjointFrom()`** method of `Set` instances takes a set and returns a boolean indicating if this set has no elements in common with the given set.

Syntax
------

```js
isDisjointFrom(other)
```

### Parameters

`other`

A `Set` object, or set-like 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:

A
 is disjoint from
B
⇔
A
∩
B
=
∅

A\text{ is disjoint from }B \Leftrightarrow A\cap B = \empty

And using Venn diagram:

![A Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/isDisjointFrom/diagram.svg)

`isDisjointFrom()` accepts set-like objects as the `other` parameter. It requires `this` to be an actual `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 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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.isDisjointFrom |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.isDisjointFrom` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.intersection()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.symmetricDifference()`
* `Set.prototype.union()`


Set[@@species] - JavaScript

Set[@@species]
==============

The **`Set[@@species]`** static accessor property is an unused accessor property specifying how to copy `Set` objects.

Syntax
------

```js
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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-set-@@species |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`
* `Symbol.species`


Set.prototype.intersection() - JavaScript

Set.prototype.intersection()
============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`intersection()`** method of `Set` instances takes a set and returns a new set containing elements in both this set and the given set.

Syntax
------

```js
intersection(other)
```

### Parameters

`other`

A `Set` object, or set-like object.

### Return value

A new `Set` object containing elements in both this set and the `other` set.

Description
-----------

In mathematical notation, *intersection* is defined as:

A
∩
B
=
{
x
∊
A
∣
x
∊
B
}

A\cap B = {x\in A\mid x\in B}

And using Venn diagram:

![A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection/diagram.svg)

`intersection()` accepts set-like objects as the `other` parameter. It requires `this` to be an actual `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 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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.intersection |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.intersection` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.symmetricDifference()`
* `Set.prototype.union()`


Set.prototype.symmetricDifference() - JavaScript

Set.prototype.symmetricDifference()
===================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`symmetricDifference()`** method of `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
symmetricDifference(other)
```

### Parameters

`other`

A `Set` object, or set-like object.

### Return value

A new `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:

A
⊖
B
=
(
A
∖
B
)
∪
(
B
∖
A
)

A\ominus B = (A\setminus B)\cup(B\setminus A)

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.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference/diagram.svg)

`symmetricDifference()` accepts set-like objects as the `other` parameter. It requires `this` to be an actual `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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.symmetricDifference |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.symmetricDifference` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.intersection()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.union()`


Set.prototype[@@iterator]() - JavaScript

Set.prototype[@@iterator]()
===========================

The **`[@@iterator]()`** method of `Set` instances implements the iterable protocol and allows `Set` objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops. It returns a set iterator object 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 `Set.prototype.values` property.

Try it
------

Syntax
------

```js
set[Symbol.iterator]()
```

### Parameters

None.

### Return value

The same return value as `Set.prototype.values()`: a new iterable iterator object 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, 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype-@@iterator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`
* `Set.prototype.entries()`
* `Set.prototype.keys()`
* `Set.prototype.values()`
* `Symbol.iterator`
* Iteration protocols


Set.prototype.difference() - JavaScript

Set.prototype.difference()
==========================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`difference()`** method of `Set` instances takes a set and returns a new set containing elements in this set but not in the given set.

Syntax
------

```js
difference(other)
```

### Parameters

`other`

A `Set` object, or set-like object.

### Return value

A new `Set` object containing elements in this set but not in the `other` set.

Description
-----------

In mathematical notation, *difference* is defined as:

A
∖
B
=
{
x
∊
A
∣
x
∉
B
}

A\setminus B = {x\in A\mid x\notin B}

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.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/difference/diagram.svg)

`difference()` accepts set-like objects as the `other` parameter. It requires `this` to be an actual `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 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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.difference |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.difference` in `core-js`
* `Set.prototype.intersection()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.symmetricDifference()`
* `Set.prototype.union()`


Set.prototype.forEach() - JavaScript

Set.prototype.forEach()
=======================

 The **`forEach()`** method of `Set` instances executes a provided function once
 for each value in this set, in insertion order.

Try it
------

Syntax
------

```js
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

A value to use as `this` when executing `callbackFn`.

### Return value

None (`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 `Set`. This is to make it
 consistent with other `forEach()` methods for `Map` and `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.

 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.foreach |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Array.prototype.forEach()`
* `Map.prototype.forEach()`


Set.prototype.isSupersetOf() - JavaScript

Set.prototype.isSupersetOf()
============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`isSupersetOf()`** method of `Set` instances takes a set and returns a boolean indicating if all elements of the given set are in this set.

Syntax
------

```js
isSupersetOf(other)
```

### Parameters

`other`

A `Set` object, or set-like 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:

A
⊇
B
⇔
∀
x
∊
B
,

x
∊
A

A\supseteq B \Leftrightarrow \forall x\in B,,x\in A

And using Venn diagram:

![A Venn diagram with two circles. A is a superset of B because B is completely contained in A.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/isSupersetOf/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 objects as the `other` parameter. It requires `this` to be an actual `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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.isSupersetOf |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.isSupersetOf` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.intersection()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSubsetOf()`
* `Set.prototype.symmetricDifference()`
* `Set.prototype.union()`


Set.prototype.add() - JavaScript

Set.prototype.add()
===================

The **`add()`** method of `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

Try it
------

Syntax
------

```js
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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.add |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`
* `Set.prototype.delete()`
* `Set.prototype.has()`


Set.prototype.has() - JavaScript

Set.prototype.has()
===================

 The **`has()`** method of `Set` instances returns a boolean indicating whether an
 element with the specified value exists in this set or not.

Try it
------

Syntax
------

```js
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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.has |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`
* `Set.prototype.add()`
* `Set.prototype.delete()`


Set() constructor - JavaScript

Set() constructor
=================

The **`Set()`** constructor creates `Set` objects.

Try it
------

Syntax
------

```js
new Set()
new Set(iterable)
```

**Note:** `Set()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`iterable` Optional

 If an iterable object 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set` in `core-js`
* `Set`


Set.prototype.entries() - JavaScript

Set.prototype.entries()
=======================

The **`entries()`** method of `Set` instances returns a new *set 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.

Try it
------

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.entries |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set.prototype.keys()`
* `Set.prototype.values()`


Set.prototype.size - JavaScript

Set.prototype.size
==================

The **`size`** accessor property of `Set` instances returns the number of (unique) elements in this set.

Try it
------

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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-set.prototype.size |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set`


Set.prototype.values() - JavaScript

Set.prototype.values()
======================

The **`values()`** method of `Set` instances returns a new *set iterator* object that contains the values for each element in this set in insertion order.

Try it
------

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.values |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set.prototype.entries()`
* `Set.prototype.keys()`


Set.prototype.isSubsetOf() - JavaScript

Set.prototype.isSubsetOf()
==========================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`isSubsetOf()`** method of `Set` instances takes a set and returns a boolean indicating if all elements of this set are in the given set.

Syntax
------

```js
isSubsetOf(other)
```

### Parameters

`other`

A `Set` object, or set-like 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:

A
⊆
B
⇔
∀
x
∊
A
,

x
∊
B

A\subseteq B \Leftrightarrow \forall x\in A,,x\in B

And using Venn diagram:

![A Venn diragram with two circles. A is a subset of B because A is completely contained in B.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/isSubsetOf/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 objects as the `other` parameter. It requires `this` to be an actual `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 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
--------------

| Specification |
| --- |
| Set methods # sec-set.prototype.isSubsetOf |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Set.prototype.isSubsetOf` in `core-js`
* `Set.prototype.difference()`
* `Set.prototype.intersection()`
* `Set.prototype.isDisjointFrom()`
* `Set.prototype.isSupersetOf()`
* `Set.prototype.symmetricDifference()`
* `Set.prototype.union()`


Set.prototype.keys() - JavaScript

Set.prototype.keys()
====================

The **`keys()`** method of `Set` instances is an alias for the `values()` method.

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new iterable iterator object.

Examples
--------

### Using keys()

The `keys()` method is exactly equivalent to the `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.keys |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Set.prototype.entries()`
* `Set.prototype.values()`


WeakRef.prototype.deref() - JavaScript

WeakRef.prototype.deref()
=========================

The **`deref()`** method of `WeakRef` instances returns this `WeakRef`'s target value, or `undefined` if the target value has been garbage-collected.

Syntax
------

```js
deref()
```

### Parameters

None.

### Return value

The target value of the WeakRef, which is either an object or a non-registered symbol. Returns `undefined` if the value has been garbage-collected.

Description
-----------

See the Notes on WeakRefs section of the `WeakRef` page for some important notes.

Examples
--------

### Using deref()

 See the Examples
 section of the `WeakRef` page for the complete example.

```js
const tick = () => {
  // Get the element from the weak reference, if it still exists
  const element = this.ref.deref();
  if (element) {
    element.textContent = ++this.count;
  } else {
    // The element doesn't exist anymore
    console.log("The element is gone.");
    this.stop();
    this.ref = null;
  }
};
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-weak-ref.prototype.deref |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WeakRef`


WeakRef() constructor - JavaScript

WeakRef() constructor
=====================

The **`WeakRef()`** constructor creates `WeakRef` objects.

Syntax
------

```js
new WeakRef(target)
```

**Note:** `WeakRef()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`target`

The target value the WeakRef should refer to (also called the *referent*). Must be an object or a non-registered symbol.

### Return value

A new `WeakRef` object referring to the given target value.

### Exceptions

`TypeError`

Thrown if `target` is not an object or a non-registered symbol.

Examples
--------

### Creating a new WeakRef object

 See the main `WeakRef`
 page for a complete example.

```js
class Counter {
  constructor(element) {
    // Remember a weak reference to a DOM element
    this.ref = new WeakRef(element);
    this.start();
  }
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-weak-ref-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WeakRef`


Keyed collections - JavaScript

Keyed collections
=================

* « Previous
* Next »

This chapter introduces collections of data which are indexed by a key; `Map` and `Set` objects contain elements which are iterable in the order of insertion.

Maps
----

### Map object

A `Map` object is a simple key/value map and can iterate its elements in insertion order.

The following code shows some basic operations with a `Map`. See also the `Map` reference page for more examples and the complete API. You can use a `for...of` loop to return an array of `[key, value]` for each iteration.

```js
const sayings = new Map();
sayings.set("dog", "woof");
sayings.set("cat", "meow");
sayings.set("elephant", "toot");
sayings.size; // 3
sayings.get("dog"); // woof
sayings.get("fox"); // undefined
sayings.has("bird"); // false
sayings.delete("dog");
sayings.has("dog"); // false

for (const [key, value] of sayings) {
  console.log(`${key} goes ${value}`);
}
// "cat goes meow"
// "elephant goes toot"

sayings.clear();
sayings.size; // 0
```

### Object and Map compared

Traditionally, objects have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. `Map` objects, however, have a few more advantages that make them better maps.

* The keys of an `Object` are strings or symbols, where they can be of any value for a `Map`.
* You can get the `size` of a `Map` easily, while you have to manually keep track of size for an `Object`.
* The iteration of maps is in insertion order of the elements.
* An `Object` has a prototype, so there are default keys in the map. (This can be bypassed using `map = Object.create(null)`.)

These three tips can help you to decide whether to use a `Map` or an `Object`:

* Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
* Use maps if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value.
* Use objects when there is logic that operates on individual elements.
### WeakMap object

A `WeakMap` is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a `WeakMap` does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any `WeakMap` become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a `WeakMap` key is symbol — more specifically, non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.

The `WeakMap` API is essentially the same as the `Map` API. However, a `WeakMap` doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration. So there is no method to obtain a list of the keys in a `WeakMap`. If there were, the list would depend on the state of garbage collection, introducing non-determinism.

For more information and example code, see also "Why WeakMap?" on the `WeakMap` reference page.

One use case of `WeakMap` objects is to store private data for an object, or to hide implementation details. The following example is from Nick Fitzgerald's blog post "Hiding Implementation Details with ECMAScript 6 WeakMaps". The private data and methods belong inside the object and are stored in the `privates` object, which is a `WeakMap`. Everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because `privates` is not exported from the module.

```js
const privates = new WeakMap();

function Public() {
  const me = {
    // Private data goes here
  };
  privates.set(this, me);
}

Public.prototype.method = function () {
  const me = privates.get(this);
  // Do stuff with private data in `me`
  // …
};

module.exports = Public;
```

Sets
----

### Set object

`Set` objects are collections of unique values. You can iterate its elements in insertion order. A value in a `Set` may only occur once; it is unique in the `Set`'s collection.

The following code shows some basic operations with a `Set`. See also the `Set` reference page for more examples and the complete API.

```js
const mySet = new Set();
mySet.add(1);
mySet.add("some text");
mySet.add("foo");

mySet.has(1); // true
mySet.delete("foo");
mySet.size; // 2

for (const item of mySet) {
  console.log(item);
}
// 1
// "some text"
```

### Converting between Array and Set

You can create an `Array` from a Set using `Array.from` or the spread syntax. Also, the `Set` constructor accepts an `Array` to convert in the other direction.

**Note:** `Set` objects store *unique values*—so any duplicate elements from an Array are deleted when converting!

```js
Array.from(mySet);
[...mySet2];

mySet2 = new Set([1, 2, 3, 4]);
```

### Array and Set compared

Traditionally, a set of elements has been stored in arrays in JavaScript in a lot of situations. The `Set` object, however, has some advantages:

* Deleting Array elements by value (`arr.splice(arr.indexOf(val), 1)`) is very slow.
* `Set` objects let you delete elements by their value. With an array, you would have to `splice` based on an element's index.
* The value `NaN` cannot be found with `indexOf` in an array.
* `Set` objects store unique values. You don't have to manually keep track of duplicates.
### WeakSet object

`WeakSet` objects are collections of garbage-collectable values, including objects and non-registered symbols. A value in the `WeakSet` may only occur once. It is unique in the `WeakSet`'s collection.

The main differences to the `Set` object are:

* In contrast to `Sets`, `WeakSets` are **collections of *objects or symbols only***, and not of arbitrary values of any type.
* The `WeakSet` is *weak*: References to objects in the collection are held weakly. If there is no other reference to an object stored in the `WeakSet`, they can be garbage collected. That also means that there is no list of current objects stored in the collection.
* `WeakSets` are not enumerable.

The use cases of `WeakSet` objects are limited. They will not leak memory, so it can be safe to use DOM elements as a key and mark them for tracking purposes, for example.

Key and value equality of Map and Set
-------------------------------------

Both the key equality of `Map` objects and the value equality of `Set` objects are based on the SameValueZero algorithm:

* Equality works like the identity comparison operator `===`.
* `-0` and `+0` are considered equal.
* `NaN` is considered equal to itself (contrary to `===`).
* « Previous
* Next »


JavaScript typed arrays - JavaScript

JavaScript typed arrays
=======================

* « Previous
* Next »

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.

Typed arrays are not intended to replace arrays for any kind of functionality. Instead, they provide developers with a familiar interface for manipulating binary data. This is useful when interacting with platform features, such as audio and video manipulation, access to raw data using WebSockets, and so forth. Each entry in a JavaScript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers.

Typed array objects share many of the same methods as arrays with similar semantics. However, typed arrays are *not* to be confused with normal arrays, as calling `Array.isArray()` on a typed array returns `false`. Moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop).

To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into *buffers* and *views*. A buffer is an object representing a chunk of data; it has no format to speak of, and offers no mechanism for accessing its contents. In order to access the memory contained in a buffer, you need to use a view. A view provides a *context* — that is, a data type, starting offset, and number of elements.

![A diagram showing how different typed arrays may be views of the same underlying buffer. Each one has a different element number and width.](/en-US/docs/Web/JavaScript/Guide/Typed_arrays/typed_arrays.png)

Buffers
-------

There are two types of buffers: `ArrayBuffer` and `SharedArrayBuffer`. Both are low-level representations of a memory span. They have "array" in their names, but they don't have much to do with arrays — you cannot read or write to them directly. Instead, buffers are generic objects that just contain raw data. In order to access the memory represented by a buffer, you need to use a view.

Buffers support the following actions:

* *Allocate*: As soon as a new buffer is created, a new memory span is allocated and initialized to `0`.
* *Copy*: Using the `slice()` method, you can efficiently copy a portion of the memory without creating views to manually copy each byte.
* *Transfer*: Using the `transfer()` and `transferToFixedLength()` methods, you can transfer ownership of the memory span to a new buffer object. This is useful when transferring data between different execution contexts without copying. After the transfer, the original buffer is no longer usable. A `SharedArrayBuffer` cannot be transferred (as the buffer is already shared by all execution contexts).
* *Resize*: Using the `resize()` method, you can resize the memory span (either claim more memory space, as long as it doesn't pass the pre-set `maxByteLength` limit, or release some memory space). `SharedArrayBuffer` can only be grown but not shrunk.

The difference between `ArrayBuffer` and `SharedArrayBuffer` is that the former is always owned by a single execution context at a time. If you pass an `ArrayBuffer` to a different execution context, it is *transferred* and the original `ArrayBuffer` becomes unusable. This ensures that only one execution context can access the memory at a time. A `SharedArrayBuffer` is not transferred when passed to a different execution context, so it can be accessed by multiple execution contexts at the same time. This may introduce race conditions when multiple threads access the same memory span, so operations such as `Atomics` methods become useful.

Views
-----

There are currently two main kinds of views: typed array views and `DataView`. Typed arrays provide utility methods that allow you to conveniently transform binary data. `DataView` is more low-level and allows granular control of how data is accessed. The ways to read and write data using the two views are very different.

Both kinds of views cause `ArrayBuffer.isView()` to return `true`. They both have the following properties:

`buffer`

The underlying buffer that the view references.

`byteOffset`

The offset, in bytes, of the view from the start of its buffer.

`byteLength`

The length, in bytes, of the view.

Both constructors accept the above three as separate arguments, although typed array constructors accept `length` as the number of elements rather than the number of bytes.

### Typed array views

Typed array views have self-descriptive names and provide views for all the usual numeric types like `Int8`, `Uint32`, `Float64` and so forth. There is one special typed array view, `Uint8ClampedArray`, which clamps the values between `0` and `255`. This is useful for Canvas data processing, for example.

| Type | Value Range | Size in bytes | Web IDL type |
| --- | --- | --- | --- |
| `Int8Array` | -128 to 127 | 1 | `byte` |
| `Uint8Array` | 0 to 255 | 1 | `octet` |
| `Uint8ClampedArray` | 0 to 255 | 1 | `octet` |
| `Int16Array` | -32768 to 32767 | 2 | `short` |
| `Uint16Array` | 0 to 65535 | 2 | `unsigned short` |
| `Int32Array` | -2147483648 to 2147483647 | 4 | `long` |
| `Uint32Array` | 0 to 4294967295 | 4 | `unsigned long` |
| `Float32Array` | `-3.4e38` to `3.4e38` | 4 | `unrestricted float` |
| `Float64Array` | `-1.8e308` to `1.8e308` | 8 | `unrestricted double` |
| `BigInt64Array` | -263 to 263 - 1 | 8 | `bigint` |
| `BigUint64Array` | 0 to 264 - 1 | 8 | `bigint` |

All typed array views have the same methods and properties, as defined by the `TypedArray` class. They only differ in the underlying data type and the size in bytes. This is discussed in more detail in Value encoding and normalization.

Typed arrays are, in principle, fixed-length, so array methods that may change the length of an array are not available. This includes `pop`, `push`, `shift`, `splice`, and `unshift`. In addition, `flat` is unavailable because there are no nested typed arrays, and related methods including `concat` and `flatMap` do not have great use cases so are unavailable. As `splice` is unavailable, so too is `toSpliced`. All other array methods are shared between `Array` and `TypedArray`.

On the other hand, `TypedArray` has the extra `set` and `subarray` methods that optimize working with multiple typed arrays that view the same buffer. The `set()` method allows setting multiple typed array indices at once, using data from another array or typed array. If the two typed arrays share the same underlying buffer, the operation may be more efficient as it's a fast memory move. The `subarray()` method creates a new typed array view that references the same buffer as the original typed array, but with a narrower span.

There's no way to directly change the length of a typed array without changing the underlying buffer. However, when the typed array views a resizable buffer and does not have a fixed `byteLength`, it is *length-tracking*, and will automatically resize to fit the underlying buffer as the resizable buffer is resized. See Behavior when viewing a resizable buffer for details.

Similar to regular arrays, you can access typed array elements using bracket notation. The corresponding bytes in the underlying buffer are retrieved and interpreted as a number. Any property access using a number (or the string representation of a number, since numbers are always converted to strings when accessing properties) will be proxied by the typed array — they never interact with the object itself. This means, for example:

* Out-of-bounds index access always returns `undefined`, without actually accessing the property on the object.
* Any attempt to write to such an out-of-bounds property has no effect: it does not throw an error but doesn't change the buffer or typed array either.
* Typed array indices appear to be configurable and writable, but any attempt to change their attributes will fail.

```js
const uint8 = new Uint8Array([1, 2, 3]);
console.log(uint8[0]); // 1

// For illustrative purposes only. Not for production code.
uint8[-1] = 0;
uint8[2.5] = 0;
uint8[NaN] = 0;
console.log(Object.keys(uint8)); // ["0", "1", "2"]
console.log(uint8[NaN]); // undefined

// Non-numeric access still works
uint8[true] = 0;
console.log(uint8[true]); // 0

Object.freeze(uint8); // TypeError: Cannot freeze array buffer views with elements
```

### DataView

The `DataView` is a low-level interface that provides a getter/setter API to read and write arbitrary data to the buffer. This is useful when dealing with different types of data, for example. Typed array views are in the native byte-order (see Endianness) of your platform. With a `DataView`, the byte-order can be controlled. By default, it's big-endian—the bytes are ordered from most significant to least significant. This can be reversed, with the bytes ordered from least significant to most significant (little-endian), using getter/setter methods.

`DataView` does not require alignment; multi-byte read and write can be started at any specified offset. The setter methods work the same way.

The following example uses a `DataView` to get the binary representation of any number:

```js
function toBinary(
  x,
  { type = "Float64", littleEndian = false, separator = " ", radix = 16 } = {},
) {
  const bytesNeeded = globalThis[`${type}Array`].BYTES\_PER\_ELEMENT;
  const dv = new DataView(new ArrayBuffer(bytesNeeded));
  dv[`set${type}`](0, x, littleEndian);
  const bytes = Array.from({ length: bytesNeeded }, (\_, i) =>
    dv
      .getUint8(i)
      .toString(radix)
      .padStart(8 / Math.log2(radix), "0"),
  );
  return bytes.join(separator);
}

console.log(toBinary(1.1)); // 3f f1 99 99 99 99 99 9a
console.log(toBinary(1.1, { littleEndian: true })); // 9a 99 99 99 99 99 f1 3f
console.log(toBinary(20, { type: "Int8", radix: 2 })); // 00010100
```

Web APIs using typed arrays
---------------------------

These are some examples of APIs that make use of typed arrays; there are others, and more are being added all the time.

`FileReader.prototype.readAsArrayBuffer()`

The `FileReader.prototype.readAsArrayBuffer()` method starts reading the contents of the specified `Blob` or `File`.

`fetch()`

The `body` option to `fetch()` can be a typed array or `ArrayBuffer`, enabling you to send these objects as the payload of a `POST` request.

`ImageData.data`

Is a `Uint8ClampedArray` representing a one-dimensional array containing the data in the RGBA order, with integer values between `0` and `255` inclusive.

Examples
--------

### Using views with buffers

First of all, we will need to create a buffer, here with a fixed length of 16-bytes:

```js
const buffer = new ArrayBuffer(16);
```

At this point, we have a chunk of memory whose bytes are all pre-initialized to 0. There's not a lot we can do with it, though. For example, we can confirm that the buffer is the right size:

```js
if (buffer.byteLength === 16) {
  console.log("Yes, it's 16 bytes.");
} else {
  console.log("Oh no, it's the wrong size!");
}
```

Before we can really work with this buffer, we need to create a view. Let's create a view that treats the data in the buffer as an array of 32-bit signed integers:

```js
const int32View = new Int32Array(buffer);
```

Now we can access the fields in the array just like a normal array:

```js
for (let i = 0; i < int32View.length; i++) {
  int32View[i] = i \* 2;
}
```

This fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values `0`, `2`, `4`, and `6`.

### Multiple views on the same data

Things start to get really interesting when you consider that you can create multiple views onto the same data. For example, given the code above, we can continue like this:

```js
const int16View = new Int16Array(buffer);

for (let i = 0; i < int16View.length; i++) {
  console.log(`Entry ${i}: ${int16View[i]}`);
}
```

Here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers. Now we get the output `0`, `0`, `2`, `0`, `4`, `0`, `6`, `0` (assuming little-endian encoding):
```

Int16Array  |   0  |  0   |   2  |  0   |   4  |  0   |   6  |  0   |
Int32Array  |      0      |      2      |      4      |      6      |
ArrayBuffer | 00 00 00 00 | 02 00 00 00 | 04 00 00 00 | 06 00 00 00 |
```

You can go a step farther, though. Consider this:

```js
int16View[0] = 32;
console.log(`Entry 0 in the 32-bit array is now ${int32View[0]}`);
```

The output from this is `"Entry 0 in the 32-bit array is now 32"`.

In other words, the two arrays are indeed viewed on the same data buffer, treating it as different formats.
```

Int16Array  |  32  |  0   |   2  |  0   |   4  |  0   |   6  |  0   |
Int32Array  |     32      |      2      |      4      |      6      |
ArrayBuffer | 00 02 00 00 | 02 00 00 00 | 04 00 00 00 | 06 00 00 00 |
```

You can do this with any view type, although if you set an integer and then read it as a floating-point number, you will probably get a strange result because the bits are interpreted differently.

```js
const float32View = new Float32Array(buffer);
console.log(float32View[0]); // 4.484155085839415e-44
```

### Reading text from a buffer

Buffers don't always represent numbers. For example, reading a file can give you a text data buffer. You can read this data out of the buffer using a typed array.

The following reads UTF-8 text using the `TextDecoder` web API:

```js
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
// Data manually written here, but pretend it was already in the buffer
uint8.set([228, 189, 160, 229, 165, 189]);
const text = new TextDecoder().decode(uint8);
console.log(text); // "你好"
```

The following reads UTF-16 text using the `String.fromCharCode()` method:

```js
const buffer = new ArrayBuffer(8);
const uint16 = new Uint16Array(buffer);
// Data manually written here, but pretend it was already in the buffer
uint16.set([0x4f60, 0x597d]);
const text = String.fromCharCode(...uint16);
console.log(text); // "你好"
```

### Working with complex data structures

By combining a single buffer with multiple views of different types, starting at different offsets into the buffer, you can interact with data objects containing multiple data types. This lets you, for example, interact with complex data structures from WebGL or data files.

Consider this C structure:

```cpp
struct someStruct {
  unsigned long id;
  char username[16];
  float amountDue;
};
```

You can access a buffer containing data in this format like this:

```js
const buffer = new ArrayBuffer(24);

// ... read the data into the buffer ...

const idView = new Uint32Array(buffer, 0, 1);
const usernameView = new Uint8Array(buffer, 4, 16);
const amountDueView = new Float32Array(buffer, 20, 1);
```

Then you can access, for example, the amount due with `amountDueView[0]`.

**Note:** The data structure alignment in a C structure is platform-dependent. Take precautions and considerations for these padding differences.

### Conversion to normal arrays

After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the `Array` prototype. This can be done using `Array.from()`:

```js
const typedArray = new Uint8Array([1, 2, 3, 4]);
const normalArray = Array.from(typedArray);
```

as well as the spread syntax:

```js
const typedArray = new Uint8Array([1, 2, 3, 4]);
const normalArray = [...typedArray];
```

See also
--------

* Faster Canvas Pixel Manipulation with Typed Arrays on hacks.mozilla.org (2011)
* Typed arrays - Binary data in the browser on web.dev (2012)
* Endianness
* `ArrayBuffer`
* `DataView`
* `TypedArray`
* `SharedArrayBuffer`
* « Previous
* Next »


Numbers and dates - JavaScript

Numbers and dates
=================

* « Previous
* Next »

This chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in JavaScript. This includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global `Math` object to perform a wide variety of mathematical operations on numbers.

Numbers
-------

In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, with a numeric precision of 53 bits). Integer values up to ±2^53 − 1 can be represented exactly.

In addition to being able to represent floating-point numbers, the number type has three symbolic values: `+``Infinity`, `-``Infinity`, and `NaN` (not-a-number).

See also JavaScript data types and structures for context with other primitive types in JavaScript.

You can use four types of number literals: decimal, binary, octal, and hexadecimal.

### Decimal numbers

```js
1234567890
42
```

Decimal literals can start with a zero (`0`) followed by another decimal digit, but if all digits after the leading `0` are smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with `0`, whether interpreted as octal or decimal, cause a syntax error in strict mode — so, use the `0o` prefix instead.

```js
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal
```

### Binary numbers

Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (`0b` or `0B`). If the digits after the `0b` are not 0 or 1, the following `SyntaxError` is thrown: "Missing binary digits after 0b".

```js
0b10000000000000000000000000000000 // 2147483648
0b01111111100000000000000000000000 // 2139095040
0B00000000011111111111111111111111 // 8388607
```

### Octal numbers

The standard syntax for octal numbers is to prefix them with `0o`. For example:

```js
0O755 // 493
0o644 // 420
```

There's also a legacy syntax for octal numbers — by prefixing the octal number with a zero: `0644 === 420` and `"\045" === "%"`. If the digits after the `0` are outside the range 0 through 7, the number will be interpreted as a decimal number.

```js
const n = 0755; // 493
const m = 0644; // 420
```

Strict mode forbids this octal syntax.

### Hexadecimal numbers

Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (`0x` or `0X`). If the digits after 0x are outside the range (0123456789ABCDEF), the following `SyntaxError` is thrown: "Identifier starts immediately after numeric literal".

```js
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF   // 81985529216486900
0XA                 // 10
```

### Exponentiation

```js
0e-5   // 0
0e+5   // 0
5e1    // 50
175e-2 // 1.75
1e3    // 1000
1e-3   // 0.001
1E3    // 1000
```

Number object
-------------

The built-in `Number` object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:

```js
const biggestNum = Number.MAX\_VALUE;
const smallestNum = Number.MIN\_VALUE;
const infiniteNum = Number.POSITIVE\_INFINITY;
const negInfiniteNum = Number.NEGATIVE\_INFINITY;
const notANum = Number.NaN;
```

You always refer to a property of the predefined `Number` object as shown above, and not as a property of a `Number` object you create yourself.

The following table summarizes the `Number` object's properties.

| Property | Description |
| --- | --- |
| `Number.MAX_VALUE` | The largest positive representable number (`1.7976931348623157e+308`) |
| `Number.MIN_VALUE` | The smallest positive representable number (`5e-324`) |
| `Number.NaN` | Special "not a number" value |
| `Number.NEGATIVE_INFINITY` | Special negative infinite value; returned on overflow |
| `Number.POSITIVE_INFINITY` | Special positive infinite value; returned on overflow |
| `Number.EPSILON` | Difference between `1` and the smallest value greater than `1` that can be represented as a `Number` (`2.220446049250313e-16`) |
| `Number.MIN_SAFE_INTEGER` | Minimum safe integer in JavaScript (−2^53 + 1, or `−9007199254740991`) |
| `Number.MAX_SAFE_INTEGER` | Maximum safe integer in JavaScript (+2^53 − 1, or `+9007199254740991`) |

| Method | Description |
| --- | --- |
| `Number.parseFloat()` | Parses a string argument and returns a floating point number. Same as the global `parseFloat()` function. |
| `Number.parseInt()` | Parses a string argument and returns an integer of the specified radix or base. Same as the global `parseInt()` function. |
| `Number.isFinite()` | Determines whether the passed value is a finite number. |
| `Number.isInteger()` | Determines whether the passed value is an integer. |
| `Number.isNaN()` | Determines whether the passed value is `NaN`. More robust version of the original global `isNaN()`. |
| `Number.isSafeInteger()` | Determines whether the provided value is a number that is a *safe integer*. |

The `Number` prototype provides methods for retrieving information from `Number` objects in various formats. The following table summarizes the methods of `Number.prototype`.

| Method | Description |
| --- | --- |
| `toExponential()` | Returns a string representing the number in exponential notation. |
| `toFixed()` | Returns a string representing the number in fixed-point notation. |
| `toPrecision()` | Returns a string representing the number to a specified precision in fixed-point notation. |

Math object
-----------

The built-in `Math` object has properties and methods for mathematical constants and functions. For example, the `Math` object's `PI` property has the value of pi (3.141…), which you would use in an application as

```js
Math.PI;
```

Similarly, standard mathematical functions are methods of `Math`. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write

```js
Math.sin(1.56);
```

Note that all trigonometric methods of `Math` take arguments in radians.

The following table summarizes the `Math` object's methods.

 Methods of
 `Math`
| Method | Description |
| --- | --- |
| `abs()` | Absolute value |
| `sin()`,
 `cos()`,
 `tan()` | Standard trigonometric functions; with the argument in radians. |
| `asin()`,
 `acos()`,
 `atan()`,
 `atan2()` | Inverse trigonometric functions; return values in radians. |
| `sinh()`,
 `cosh()`,
 `tanh()` | Hyperbolic functions; argument in hyperbolic angle. |
| `asinh()`,
 `acosh()`,
 `atanh()` | Inverse hyperbolic functions; return values in hyperbolic angle. |
|
`pow()`,
 `exp()`,
 `expm1()`,
 `log()`,
 `log10()`,
 `log1p()`,
 `log2()`
 | Exponential and logarithmic functions. |
| `floor()`,
 `ceil()` |
 Returns the largest/smallest integer less/greater than or equal to an
 argument.
  |
| `min()`,
 `max()` |
 Returns the minimum or maximum (respectively) value of a comma separated
 list of numbers as arguments.
  |
| `random()` | Returns a random number between 0 and 1. |
| `round()`,
 `fround()`,
 `trunc()`,
  | Rounding and truncation functions. |
| `sqrt()`,
 `cbrt()`,
 `hypot()` | Square root, cube root, Square root of the sum of square arguments. |
| `sign()` |
 The sign of a number, indicating whether the number is positive,
 negative or zero.
  |
| `clz32()`,`imul()` |
 Number of leading zero bits in the 32-bit binary representation.The
 result of the C-like 32-bit multiplication of the two arguments.
  |

Unlike many other objects, you never create a `Math` object of your own. You always use the built-in `Math` object.

BigInts
-------

One shortcoming of number values is they only have 64 bits. In practice, due to using IEEE 754 encoding, they cannot represent any integer larger than `Number.MAX_SAFE_INTEGER` (which is 253 - 1) accurately. To solve the need of encoding binary data and to interoperate with other languages that offer wide integers like `i64` (64-bit integers) and `i128` (128-bit integers), JavaScript also offers another data type to represent *arbitrarily large integers*: `BigInt`.

A BigInt can be defined as an integer literal suffixed by `n`:

```js
const b1 = 123n;
// Can be arbitrarily large.
const b2 = -1234567890987654321n;
```

BigInts can also be constructed from number values or string values using the `BigInt` constructor.

```js
const b1 = BigInt(123);
// Using a string prevents loss of precision, since long number
// literals don't represent what they seem like.
const b2 = BigInt("-1234567890987654321");
```

Conceptually, a BigInt is just an arbitrarily long sequence of bits which encodes an integer. You can safely do any arithmetic operations without losing precision or over-/underflowing.

```js
const integer = 12 \*\* 34; // 4.9222352429520264e+36; only has limited precision
const bigint = 12n \*\* 34n; // 4922235242952026704037113243122008064n
```

Compared to numbers, BigInt values yield higher precision when representing large *integers*; however, they cannot represent *floating-point numbers*. For example, division would round to zero:

```js
const bigintDiv = 5n / 2n; // 2n, because there's no 2.5 in BigInt
```

`Math` functions cannot be used on BigInt values. There is an open proposal to overload certain `Math` functions like `Math.max()` to allow BigInt values.

Choosing between BigInt and number depends on your use-case and your input's range. The precision of numbers should be able to accommodate most day-to-day tasks already, and BigInts are most suitable for handling binary data.

Read more about what you can do with BigInt values in the Expressions and Operators section, or the BigInt reference.

Date object
-----------

JavaScript does not have a date data type. However, you can use the `Date` object and its methods to work with dates and times in your applications. The `Date` object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called the epoch.

The `Date` object range is -100,000,000 days to 100,000,000 days relative to the epoch.

To create a `Date` object:

```js
const dateObjectName = new Date([parameters]);
```

where `dateObjectName` is the name of the `Date` object being created; it can be a new object or a property of an existing object.

Calling `Date` without the `new` keyword returns a string representing the current date and time.

The `parameters` in the preceding syntax can be any of the following:

* Nothing: creates today's date and time. For example, `today = new Date();`.
* A string representing a date, in many different forms. The exact forms supported differ among engines, but the following form is always supported: `YYYY-MM-DDTHH:mm:ss.sssZ`. For example, `xmas95 = new Date("1995-12-25")`. If you omit hours, minutes, or seconds, the value will be set to zero.
* A set of integer values for year, month, and day. For example, `xmas95 = new Date(1995, 11, 25)`.
* A set of integer values for year, month, day, hour, minute, and seconds. For example, `xmas95 = new Date(1995, 11, 25, 9, 30, 0);`.
### Methods of the Date object

The `Date` object methods for handling dates and times fall into these broad categories:

* "set" methods, for setting date and time values in `Date` objects.
* "get" methods, for getting date and time values from `Date` objects.
* "to" methods, for returning string values from `Date` objects.
* parse and UTC methods, for parsing `Date` strings.

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a `getDay` method that returns the day of the week, but no corresponding `setDay` method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

* Seconds and minutes: 0 to 59
* Hours: 0 to 23
* Day: 0 (Sunday) to 6 (Saturday)
* Date: 1 to 31 (day of the month)
* Months: 0 (January) to 11 (December)
* Year: years since 1900

For example, suppose you define the following date:

```js
const xmas95 = new Date("1995-12-25");
```

Then `xmas95.getMonth()` returns 11, and `xmas95.getFullYear()` returns 1995.

The `getTime` and `setTime` methods are useful for comparing dates. The `getTime` method returns the number of milliseconds since the epoch for a `Date` object.

For example, the following code displays the number of days left in the current year:

```js
const today = new Date();
const endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
const msPerDay = 24 \* 60 \* 60 \* 1000; // Number of milliseconds per day
let daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
daysLeft = Math.round(daysLeft); // Returns days left in the year
```

This example creates a `Date` object named `today` that contains today's date. It then creates a `Date` object named `endYear` and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between `today` and `endYear`, using `getTime` and rounding to a whole number of days.

The `parse` method is useful for assigning values from date strings to existing `Date` objects. For example, the following code uses `parse` and `setTime` to assign a date value to the `ipoDate` object:

```js
const ipoDate = new Date();
ipoDate.setTime(Date.parse("Aug 9, 1995"));
```

### Example

In the following example, the function `JSClock()` returns the time in the format of a digital clock.

```js
function JSClock() {
  const time = new Date();
  const hour = time.getHours();
  const minute = time.getMinutes();
  const second = time.getSeconds();
  let temp = String(hour % 12);
  if (temp === "0") {
    temp = "12";
  }
  temp += (minute < 10 ? ":0" : ":") + minute;
  temp += (second < 10 ? ":0" : ":") + second;
  temp += hour >= 12 ? " P.M." : " A.M.";
  return temp;
}
```

The `JSClock` function first creates a new `Date` object called `time`; since no arguments are given, time is created with the current date and time. Then calls to the `getHours`, `getMinutes`, and `getSeconds` methods assign the value of the current hour, minute, and second to `hour`, `minute`, and `second`.

The following statements build a string value based on the time. The first statement creates a variable `temp`. Its value is `hour % 12`, which is `hour` in the 12-hour system. Then, if the hour is `0`, it gets re-assigned to `12`, so that midnights and noons are displayed as `12:00` instead of `0:00`.

The next statement appends a `minute` value to `temp`. If the value of `minute` is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to `temp` in the same way.

Finally, a conditional expression appends "P.M." to `temp` if `hour` is 12 or greater; otherwise, it appends "A.M." to `temp`.

* « Previous
* Next »