Iterator.prototype.forEach() - JavaScript

Iterator.prototype.forEach()
============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`forEach()`** method of `Iterator` instances is similar to `Array.prototype.forEach()`: it executes a provided function once for each element produced by the iterator.

Syntax
------

```js
forEach(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. Its return value is discarded. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

`undefined`.

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

`forEach()` iterates the iterator and invokes the `callbackFn` function once for each element. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.

Examples
--------

### Using forEach()

```js
new Set([1, 2, 3]).values().forEach((v) => console.log(v));

// Logs:
// 1
// 2
// 3
```

This is equivalent to:

```js
for (const v of new Set([1, 2, 3]).values()) {
  console.log(v);
}
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.foreach |

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

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

See also
--------

* Polyfill of `Iterator.prototype.forEach` in `core-js`
* `Iterator`
* `Iterator.prototype.find()`
* `Iterator.prototype.map()`
* `Iterator.prototype.filter()`
* `Iterator.prototype.every()`
* `Iterator.prototype.some()`
* `Array.prototype.forEach()`


Iterator() constructor - JavaScript

Iterator() constructor
======================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`Iterator()`** constructor is intended to be used as the superclass of other classes that create iterators. It throws an error when constructed by itself.

Syntax
------

```js
new Iterator()
```

**Note:** `Iterator()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`. In addition, `Iterator()` cannot actually be constructed itself — it's usually implicitly constructed through `super()` calls inside the constructor of a subclass.

### Parameters

None.

### Return value

A new `Iterator` object.

### Exceptions

`TypeError`

When `new.target` is the `Iterator` function itself, i.e. when the `Iterator` constructor itself is constructed.

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

`Iterator` represents an *abstract class* — a class that provides common utilities for its subclasses, but is not intended to be instantiated itself. It is the superclass of all other iterator classes, and is used to create subclasses that implement specific iteration algorithms — namely, all subclasses of `Iterator` must implement a `next()` method as required by the iterator protocol. Because `Iterator` doesn't actually provide the `next()` method, it doesn't make sense to construct an `Iterator` directly.

You can also use `Iterator.from()` to create an `Iterator` instance from an existing iterable or iterator object.

Examples
--------

### Subclassing Iterator

The following example defines a custom data structure, `Range`, which allows iteration. The simplest way to make an object iterable is to provide an `[@@iterator]()` method in the form of a generator function:

```js
class Range {
  #start;
  #end;
  #step;

  constructor(start, end, step = 1) {
    this.#start = start;
    this.#end = end;
    this.#step = step;
  }

  \*[Symbol.iterator]() {
    for (let value = this.#start; value <= this.#end; value += this.#step) {
      yield value;
    }
  }
}

const range = new Range(1, 5);
for (const num of range) {
  console.log(num);
}
```

This works, but it isn't as nice as how built-in iterators work. There are two problems:

* The returned iterator inherits from `Generator`, which means modifications to `Generator.prototype` are going to affect the returned iterator, which is a leak of abstraction.
* The returned iterator does not inherit from a custom prototype, which makes it harder if we intend to add extra methods to the iterator.

We can mimic the implementation of built-in iterators, such as map iterators, by subclassing `Iterator`. This enables us to define extra properties, such as `@@toStringTag`, while making the iterator helper methods available on the returned iterator.

```js
class Range {
  #start;
  #end;
  #step;

  constructor(start, end, step = 1) {
    this.#start = start;
    this.#end = end;
    this.#step = step;
  }

  static #RangeIterator = class extends Iterator {
    #cur;
    #s;
    #e;
    constructor(range) {
      super();
      this.#cur = range.#start;
      this.#s = range.#step;
      this.#e = range.#end;
    }
    static {
      Object.defineProperty(this.prototype, Symbol.toStringTag, {
        value: "Range Iterator",
        configurable: true,
        enumerable: false,
        writable: false,
      });

      // Avoid #RangeIterator from being accessible outside
      delete this.prototype.constructor;
    }
    next() {
      if (this.#cur > this.#e) {
        return { value: undefined, done: true };
      }
      const res = { value: this.#cur, done: false };
      this.#cur += this.#s;
      return res;
    }
  };

  [Symbol.iterator]() {
    return new Range.#RangeIterator(this);
  }
}

const range = new Range(1, 5);
for (const num of range) {
  console.log(num);
}
```

The subclassing pattern is useful if you want to create many custom iterators. If you have an existing iterable or iterator object which doesn't inherit from `Iterator`, and you just want to call iterator helper methods on it, you can use `Iterator.from()` to create a one-time `Iterator` instance.

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

| Specification |
| --- |
| Iterator Helpers # sec-iterator-constructor |

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

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

See also
--------

* Polyfill of `Iterator` in `core-js`
* `Iterator`
* `Iterator.from()`


Iterator.from() - JavaScript

Iterator.from()
===============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`Iterator.from()`** static method creates a new `Iterator` object from an iterator or iterable object.

Syntax
------

```js
from(object)
```

### Parameters

`object`

An object that implements the iterable protocol or the iterator protocol.

### Return value

If `object` is an iterable, its `@@iterator` method is called to obtain the iterator. Otherwise, `object` is assumed to be an iterator. If the iterator is already `instanceof` `Iterator` (which means it has `Iterator.prototype` in its prototype chain), it is returned directly. Otherwise, a new `Iterator` object is created that wraps the original iterator.

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

This method exists to convert custom iterators, probably exported by libraries, to proper iterators. All iterator objects returned by `Iterator.from()` inherit from a common prototype object, which has the following methods:

`next()`

Calls the underlying iterator's `next()` method and returns the result.

`return()`

Calls the underlying iterator's `return()` method and returns the result, or returns `{ value: undefined, done: true }` if the underlying iterator doesn't have a `return()` method.

Examples
--------

### Converting an iterable to a proper iterator

Because `obj` is already an iterable that returns a proper iterator when its `@@iterator` method is called, `Iterator.from(obj)` returns the same iterator.

```js
const iterator = (function\* () {
  yield 1;
  yield 2;
  yield 3;
})();

const obj = {
  [Symbol.iterator]() {
    return iterator;
  },
};

const iterator2 = Iterator.from(obj);
console.log(iterator2 === iterator); // true
```

Because `obj2` is an iterable that returns a non-proper iterator when its `@@iterator` method is called, `Iterator.from(obj2)` returns a new iterator that wraps the original iterator.

```js
const iterator = {
  current: 0,
  next() {
    return { value: this.current++, done: false };
  },
};

const obj2 = {
  [Symbol.iterator]() {
    return iterator;
  },
};

const iterator2 = Iterator.from(obj2);
console.log(iterator2 === iterator); // false
console.log(iterator2.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
```

### Converting an iterator to a proper iterator

Because `obj` is already a proper iterator, `Iterator.from(obj)` returns itself.

```js
const obj = (function\* () {
  yield 1;
  yield 2;
  yield 3;
})();

const iterator = Iterator.from(obj);
console.log(iterator === obj); // true
```

Because `obj2` is a non-proper iterator, `Iterator.from(obj2)` returns a new iterator that wraps the original iterator.

```js
const obj2 = {
  current: 0,
  next() {
    return { value: this.current++, done: false };
  },
};

const iterator = Iterator.from(obj2);
console.log(iterator === obj2); // false
console.log(iterator.next()); // { value: 0, done: false }
console.log(obj2.next()); // { value: 1, done: false }
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iterator.from |

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

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

See also
--------

* Polyfill of `Iterator.from` in `core-js`
* `Iterator`
* `Array.from()`


Iterator.prototype.take() - JavaScript

Iterator.prototype.take()
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`take()`** method of `Iterator` instances returns a new iterator helper that yields the given number of elements in this iterator and then terminates.

Syntax
------

```js
take(limit)
```

### Parameters

`limit`

The number of elements to take from the start of the iteration.

### Return value

A new iterator helper. The returned iterator helper yields the elements in the original iterator one-by-one, and then completes (the `next()` method produces `{ value: undefined, done: true }`) once `limit` elements have been yielded, or when the original iterator is exhausted, whichever comes first.

### Exceptions

`RangeError`

Thrown if `limit` becomes `NaN` or negative when converted to an integer.

Examples
--------

### Using take()

The following example creates an iterator that yields terms in the Fibonacci sequence, and then logs the first three terms:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci().take(3);
console.log(seq.next().value); // 1
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // undefined
```

### Using take() with a for...of loop

`take()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a `for...of` loop:

```js
for (const n of fibonacci().take(5)) {
  console.log(n);
}

// Logs:
// 1
// 1
// 2
// 3
// 5
```

Because `fibonacci()` is an infinite iterator, you can't use a `for` loop to iterate it directly.

### Combining drop() with take()

You can combine `drop()` with `Iterator.prototype.take()` to get a slice of an iterator:

```js
for (const n of fibonacci().drop(2).take(5)) {
  // Drops the first two elements, then takes the next five
  console.log(n);
}
// Logs:
// 2
// 3
// 5
// 8
// 13

for (const n of fibonacci().take(5).drop(2)) {
  // Takes the first five elements, then drops the first two
  console.log(n);
}
// Logs:
// 2
// 3
// 5
```

### Lower and upper bounds of take count

When the `limit` is negative or `NaN`, a `RangeError` is thrown:

```js
fibonacci().take(-1); // RangeError: -1 must be positive
fibonacci().take(undefined); // RangeError: undefined must be positive
```

When the `limit` is larger than the total number of elements the iterator can produce (such as `Infinity`), the returned iterator helper has essentially the same behavior as the original iterator:

```js
for (const n of new Set([1, 2, 3]).values().take(Infinity)) {
  console.log(n);
}

// Logs:
// 1
// 2
// 3
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.take |

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

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

See also
--------

* Polyfill of `Iterator.prototype.take` in `core-js`
* `Iterator`
* `Iterator.prototype.drop()`


Iterator.prototype.reduce() - JavaScript

Iterator.prototype.reduce()
===========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`reduce()`** method of `Iterator` instances is similar to `Array.prototype.reduce`: it executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

Syntax
------

```js
reduce(callbackFn)
reduce(callbackFn, initialValue)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments:

`accumulator`

The value resulting from the previous call to `callbackFn`. On the first call, its value is `initialValue` if the latter is specified; otherwise its value is the first element of the iterator.

`currentValue`

The value of the current element. On the first call, its value is the first element of the iterator if `initialValue` is specified; otherwise its value is the second element.

`currentIndex`

The index position of `currentValue`. On the first call, its value is `0` if `initialValue` is specified, otherwise `1`.

`initialValue` Optional

A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first element as `currentValue`. If `initialValue` is *not* specified, `accumulator` is initialized to the first element, and `callbackFn` starts executing with the second element as `currentValue`. In this case, if the iterator is empty (so that there's no first value to return as `accumulator`), an error is thrown.

### Return value

The value that results from running the "reducer" callback function to completion over the entire iterator.

### Exceptions

`TypeError`

Thrown if the iterator contains no elements and `initialValue` is not provided.

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

See `Array.prototype.reduce()` for details about how `reduce()` works. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy.

Examples
--------

### Using reduce()

The following example creates an iterator that yields terms in the Fibonacci sequence, and then sums the first ten terms:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

console.log(
  fibonacci()
    .take(10)
    .reduce((a, b) => a + b),
); // 143
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.reduce |

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

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

See also
--------

* Polyfill of `Iterator.prototype.reduce` in `core-js`
* `Iterator`
* `Iterator.prototype.map()`
* `Iterator.prototype.flatMap()`
* `Array.prototype.reduce()`


Iterator.prototype.every() - JavaScript

Iterator.prototype.every()
==========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`every()`** method of `Iterator` instances is similar to `Array.prototype.every()`: it tests whether all elements produced by the iterator pass the test implemented by the provided function. It returns a boolean value.

Syntax
------

```js
every(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

`true` if `callbackFn` returns a truthy value for every element. Otherwise, `false`.

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

`every()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns `false` immediately if the callback function returns a falsy value. Otherwise, it iterates until the end of the iterator and returns `true`. If `every()` returns `false`, the underlying iterator is closed by calling its `return()` method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `every()` returns `false` as soon as the first falsy value is found. If the `callbackFn` always returns a truthy value, the method never returns.

Examples
--------

### Using every()

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const isEven = (x) => x % 2 === 0;
console.log(fibonacci().every(isEven)); // false

const isPositive = (x) => x > 0;
console.log(fibonacci().take(10).every(isPositive)); // true
console.log(fibonacci().every(isPositive)); // Never completes
```

Calling `every()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

```js
const seq = fibonacci();
console.log(seq.every(isEven)); // false
console.log(seq.next()); // { value: undefined, done: true }
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.every |

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

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

See also
--------

* Polyfill of `Iterator.prototype.every` in `core-js`
* `Iterator`
* `Iterator.prototype.find()`
* `Iterator.prototype.some()`
* `Array.prototype.every()`


Iterator.prototype.drop() - JavaScript

Iterator.prototype.drop()
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`drop()`** method of `Iterator` instances returns a new iterator helper that skips the given number of elements at the start of this iterator.

Syntax
------

```js
drop(limit)
```

### Parameters

`limit`

The number of elements to drop from the start of the iteration.

### Return value

A new iterator helper. The first time the returned iterator helper's `next()` method is called, the current iterator is immediately advanced by `limit` elements, and then the next element (the `limit+1`-th element) is yielded. The iterator helper then yields the remaining elements one-by-one. If the current iterator has fewer than `limit` elements, the new iterator helper will be immediately completed the first time `next()` is called.

### Exceptions

`RangeError`

Thrown if `limit` becomes `NaN` or negative when converted to an integer.

Examples
--------

### Using drop()

The following example creates an iterator that yields terms in the Fibonacci sequence, starting from the 3rd term by dropping the first two terms:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci().drop(2);
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
```

This is equivalent to:

```js
const seq = fibonacci();
seq.next();
seq.next();
```

### Using drop() with a for...of loop

`drop()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a `for...of` loop:

```js
for (const n of fibonacci().drop(2)) {
  console.log(n);
  if (n > 30) {
    break;
  }
}

// Logs:
// 2
// 3
// 5
// 8
// 13
// 21
// 34
```

### Combining drop() with take()

You can combine `drop()` with `Iterator.prototype.take()` to get a slice of an iterator:

```js
for (const n of fibonacci().drop(2).take(5)) {
  // Drops the first two elements, then takes the next five
  console.log(n);
}
// Logs:
// 2
// 3
// 5
// 8
// 13

for (const n of fibonacci().take(5).drop(2)) {
  // Takes the first five elements, then drops the first two
  console.log(n);
}
// Logs:
// 2
// 3
// 5
```

### Lower and upper bounds of drop count

When the `limit` is negative or `NaN`, a `RangeError` is thrown:

```js
fibonacci().drop(-1); // RangeError: -1 must be positive
fibonacci().drop(undefined); // RangeError: undefined must be positive
```

When the `limit` is larger than the total number of elements the iterator can produce (such as `Infinity`), the returned iterator helper will instantly drop all elements and then be completed the first time `next()` is called. If the current iterator is infinite, the returned iterator helper will never complete.

```js
fibonacci().drop(Infinity).next(); // Never ends
new Set([1, 2, 3]).values().drop(Infinity).next(); // { value: undefined, done: true }
new Set([1, 2, 3]).values().drop(4).next(); // { value: undefined, done: true }
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.drop |

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

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

See also
--------

* Polyfill of `Iterator.prototype.drop` in `core-js`
* `Iterator`
* `Iterator.prototype.take()`


Iterator.prototype.flatMap() - JavaScript

Iterator.prototype.flatMap()
============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`flatMap()`** method of `Iterator` instances returns a new iterator helper that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).

Syntax
------

```js
flatMap(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. It should return an iterator or iterable that yields elements to be yielded by `flatMap()`, or a single non-iterator/iterable value to be yielded. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

### Return value

A new iterator helper. The first time the iterator helper's `next()` method is called, it calls `callbackFn` on the first element produced by the underlying iterator, and the return value, which should be an iterator or iterable, is yielded one-by-one by the iterator helper (like `yield*`). The next element is fetched from the underlying iterator when the previous one returned by `callbackFn` is completed. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`).

### Exceptions

`TypeError`

Thrown if `callbackFn` returns a non-iterator/iterable value or a string primitive.

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

`flatMap` accepts two kinds of return values from `callbackFn`: an iterator or iterable. They are handled in the same way as `Iterator.from()`: if the return value is iterable, the `@@iterator` method is called and the return value is used; otherwise, the return value is treated as an iterator and its `next()` method is called.

```js
[1, 2, 3]
  .values()
  .flatMap((x) => {
    let itDone = false;
    const it = {
      next() {
        if (itDone) {
          return { value: undefined, done: true };
        }
        itDone = true;
        return { value: x, done: false };
      },
    };
    switch (x) {
      case 1:
        // An iterable that's not an iterator
        return { [Symbol.iterator]: () => it };
      case 2:
        // An iterator that's not an iterable
        return it;
      case 3:
        // An iterable iterator is treated as an iterable
        return {
          ...it,
          [Symbol.iterator]() {
            console.log("@@iterator called");
            return it;
          },
        };
    }
  })
  .toArray();
// Logs "@@iterator called"
// Returns [1, 2, 3]
```

Examples
--------

### Merging maps

The following example merges two `Map` objects into one:

```js
const map1 = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
]);
const map2 = new Map([
  ["d", 4],
  ["e", 5],
  ["f", 6],
]);

const merged = new Map([map1, map2].values().flatMap((x) => x));
console.log(merged.get("a")); // 1
console.log(merged.get("e")); // 5
```

This avoids creating any temporary copies of the map's content. Note that the array `[map1, map2]` must first be converted to an iterator (using `Array.prototype.values()`), because `Array.prototype.flatMap()` only flattens arrays, not iterables.

```js
new Map([map1, map2].flatMap((x) => x)); // Map(1) {undefined => undefined}
```

### Returning strings

Strings are iterable, but `flatMap()` specifically rejects string primitives returned from `callbackFn`, this is because the behavior of iterating by code points is often not what you want.

```js
[1, 2, 3]
  .values()
  .flatMap((x) => String(x))
  .toArray(); // TypeError: Iterator.prototype.flatMap called on non-object
```

You may want to wrap it in an array instead so the entire string is yielded as one:

```js
[1, 2, 3]
  .values()
  .flatMap((x) => [String(x)])
  .toArray(); // ['1', '2', '3']
```

Or, if the behavior of iterating by code points is intended, you can use `Iterator.from()` to convert it to a proper iterator:

```js
[1, 2, 3]
  .values()
  .flatMap((x) => Iterator.from(String(x \* 10)))
  .toArray();
// ['1', '0', '2', '0', '3', '0']
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.flatmap |

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

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

See also
--------

* Polyfill of `Iterator.prototype.flatMap` in `core-js`


Iterator.prototype.some() - JavaScript

Iterator.prototype.some()
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`some()`** method of `Iterator` instances is similar to `Array.prototype.some()`: it tests whether at least one element in the array passes the test implemented by the provided function. It returns a boolean value.

Syntax
------

```js
some(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

`true` if the callback function returns a truthy value for at least one element. Otherwise, `false`.

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

`some()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns `true` immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns `false`. If `some()` returns `true`, the underlying iterator is closed by calling its `return()` method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `some()` returns `true` as soon as the first truthy value is found. If the `callbackFn` always returns a falsy value, the method never returns.

Examples
--------

### Using some()

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const isEven = (x) => x % 2 === 0;
console.log(fibonacci().some(isEven)); // true

const isNegative = (x) => x < 0;
const isPositive = (x) => x > 0;
console.log(fibonacci().take(10).some(isPositive)); // false
console.log(fibonacci().some(isNegative)); // Never completes
```

Calling `some()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

```js
const seq = fibonacci();
console.log(seq.some(isEven)); // true
console.log(seq.next()); // { value: undefined, done: true }
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.some |

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

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

See also
--------

* Polyfill of `Iterator.prototype.some` in `core-js`
* `Iterator`
* `Iterator.prototype.every()`
* `Iterator.prototype.find()`
* `Array.prototype.some()`


Iterator.prototype.map() - JavaScript

Iterator.prototype.map()
========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`map()`** method of `Iterator` instances returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function.

Syntax
------

```js
map(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. Its return value is yielded by the iterator helper. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

A new iterator helper. Each time the iterator helper's `next()` method is called, it gets the next element from the underlying iterator, applies `callbackFn`, and yields the return value. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`).

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

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `map()` allows you to create a new iterator that, when iterated, produces transformed elements.

Examples
--------

### Using map()

The following example creates an iterator that yields terms in the Fibonacci sequence, transforms it into a new sequence with each term squared, and then reads the first few terms:

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const seq = fibonacci().map((x) => x \*\* 2);
console.log(seq.next().value); // 1
console.log(seq.next().value); // 1
console.log(seq.next().value); // 4
```

### Using map() with a for...of loop

`map()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a `for...of` loop:

```js
for (const n of fibonacci().map((x) => x \*\* 2)) {
  console.log(n);
  if (n > 30) {
    break;
  }
}

// Logs:
// 1
// 1
// 4
// 9
// 25
// 64
```

This is equivalent to:

```js
for (const n of fibonacci()) {
  const n2 = n \*\* 2;
  console.log(n2);
  if (n2 > 30) {
    break;
  }
}
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.map |

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

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

See also
--------

* Polyfill of `Iterator.prototype.map` in `core-js`


Iterator.prototype.find() - JavaScript

Iterator.prototype.find()
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`find()`** method of `Iterator` instances is similar to `Array.prototype.find()`: it returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, `undefined` is returned.

Syntax
------

```js
find(callbackFn)
```

### Parameters

`callbackFn`

A function to execute for each element produced by the iterator. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

The first element produced by the iterator that satisfies the provided testing function. Otherwise, `undefined` is returned.

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

`find()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns the element immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns `undefined`. If `find()` returns an element, the underlying iterator is closed by calling its `return()` method.

The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `find()` returns the first satisfying element as soon as it is found. If the `callbackFn` always returns a falsy value, the method never returns.

Examples
--------

### Using find()

```js
function\* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const isEven = (x) => x % 2 === 0;
console.log(fibonacci().find(isEven)); // 2

const isNegative = (x) => x < 0;
console.log(fibonacci().take(10).find(isNegative)); // undefined
console.log(fibonacci().find(isNegative)); // Never completes
```

Calling `find()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

```js
const seq = fibonacci();
console.log(seq.find(isEven)); // 2
console.log(seq.next()); // { value: undefined, done: true }
```

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

| Specification |
| --- |
| Iterator Helpers # sec-iteratorprototype.find |

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

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

See also
--------

* Polyfill of `Iterator.prototype.find` in `core-js`


URIError() constructor - JavaScript

URIError() constructor
======================

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

Syntax
------

```js
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`. Both create a new `URIError` instance.

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

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

The name of the file containing the code that caused the exception.

`lineNumber` Optional
Non-standard

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-nativeerror-constructors |

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

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

See also
--------

* `Error`
* `decodeURI()`
* `decodeURIComponent()`
* `encodeURI()`
* `encodeURIComponent()`


Int8Array() constructor - JavaScript

Int8Array() constructor
=======================

The **`Int8Array()`** constructor creates `Int8Array` objects. The contents are initialized to `0`.

Syntax
------

```js
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`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

See `TypedArray`.

### Exceptions

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-constructors |

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

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

See also
--------

* Polyfill of `Int8Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


Uint32Array() constructor - JavaScript

Uint32Array() constructor
=========================

The **`Uint32Array()`** constructor creates `Uint32Array` objects. The contents are initialized to `0`.

Syntax
------

```js
new Uint32Array()
new Uint32Array(length)
new Uint32Array(typedArray)
new Uint32Array(object)

new Uint32Array(buffer)
new Uint32Array(buffer, byteOffset)
new Uint32Array(buffer, byteOffset, length)
```

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a Uint32Array

```js
// From a length
const uint32 = new Uint32Array(2);
uint32[0] = 42;
console.log(uint32[0]); // 42
console.log(uint32.length); // 2
console.log(uint32.BYTES\_PER\_ELEMENT); // 4

// From an array
const x = new Uint32Array([21, 31]);
console.log(x[1]); // 31

// From another TypedArray
const y = new Uint32Array(x);
console.log(y[0]); // 21

// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Uint32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const uint32FromIterable = new Uint32Array(iterable);
console.log(uint32FromIterable);
// Uint32Array [1, 2, 3]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-constructors |

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

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

See also
--------

* Polyfill of `Uint32Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


TypeError() constructor - JavaScript

TypeError() constructor
=======================

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

Syntax
------

```js
new TypeError()
new TypeError(message)
new TypeError(message, options)
new TypeError(message, fileName)
new TypeError(message, fileName, lineNumber)

TypeError()
TypeError(message)
TypeError(message, options)
TypeError(message, fileName)
TypeError(message, fileName, lineNumber)
```

**Note:** `TypeError()` can be called with or without `new`. Both create a new `TypeError` instance.

### Parameters

`message` Optional

Human-readable description of the error

`options` Optional

An object that has the following properties:

`cause` Optional

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

The name of the file containing the code that caused the exception

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

### Catching a TypeError

```js
try {
  null.f();
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "null has no properties"
  console.log(e.name); // "TypeError"
  console.log(e.stack); // Stack of the error
}
```

### Creating a TypeError

```js
try {
  throw new TypeError("Hello");
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "TypeError"
  console.log(e.stack); // Stack of the error
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-nativeerror-constructors |

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

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

See also
--------

* `Error`


String.prototype.fixed() - JavaScript

String.prototype.fixed()
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`fixed()`** method of `String` values creates a string that embeds this string in a `<tt>` element (`<tt>str</tt>`), which causes this string to be displayed in a fixed-width font.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `fixed()`, the `<tt>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

Syntax
------

```js
fixed()
```

### Parameters

None.

### Return value

A string beginning with a `<tt>` start tag, then the text `str`, and then a `</tt>` end tag.

Examples
--------

### Using fixed()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.fixed();
```

This will create the following HTML:

```html
<tt>Hello, world</tt>
```

**Warning:** This markup is invalid, because `tt` is no longer a valid element.

Instead of using `fixed()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate `font-family` through the `element.style` attribute:

```js
document.getElementById("yourElemId").style.fontFamily = "monospace";
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.fixed |

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

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

See also
--------

* Polyfill of `String.prototype.fixed` in `core-js`
* HTML wrapper methods
* `<tt>`


String.prototype.split() - JavaScript

String.prototype.split()
========================

The **`split()`** method of `String` values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Try it
------

Syntax
------

```js
split(separator)
split(separator, limit)
```

### Parameters

`separator`

The pattern describing where each split should occur. Can be `undefined`, a string, or an object with a `Symbol.split` method — the typical example being a regular expression. Omitting `separator` or passing `undefined` causes `split()` to return an array with the calling string as a single element. All values that are not `undefined` or objects with a `@@split` method are coerced to strings.

`limit` Optional

A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all.

* The array may contain fewer entries than `limit` if the end of the string is reached before the limit is reached.
* If `limit` is `0`, `[]` is returned.

### Return value

An `Array` of strings, split at each point where the `separator` occurs in the given string.

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

If `separator` is a non-empty string, the target string is split by all matches of the `separator` without including `separator` in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like `myString.split("\t")`. If `separator` contains multiple characters, that entire character sequence must be found in order to split. If `separator` appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If `separator` does not occur in `str`, the returned array contains one element consisting of the entire string.

If `separator` is an empty string (`""`), `str` is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.

**Note:** `"".split("")` is therefore the only way to produce an empty array when a string is passed as `separator` and `limit` is not `0`.

**Warning:** When the empty string (`""`) is used as a separator, the string is **not** split by *user-perceived characters* (grapheme clusters) or unicode characters (code points), but by UTF-16 code units. This destroys surrogate pairs. See "How do you get a string to a character array in JavaScript?" on StackOverflow.

If `separator` is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is Unicode-aware.

```js
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]
```

If `separator` is a regular expression with capturing groups, then each time `separator` matches, the captured groups (including any `undefined` results) are spliced into the output array. This behavior is specified by the regexp's `Symbol.split` method.

If `separator` is an object with a `Symbol.split` method, that method is called with the target string and `limit` as arguments, and `this` set to the object. Its return value becomes the return value of `split`.

Any other value will be coerced to a string before being used as separator.

Examples
--------

### Using split()

When the string is empty and a non-empty separator is specified, `split()` returns `[""]`. If the string and separator are both empty strings, an empty array is returned.

```js
const emptyString = "";

// string is empty and separator is non-empty
console.log(emptyString.split("a"));
// [""]

// string and separator are both empty strings
console.log(emptyString.split(emptyString));
// []
```

 The following example defines a function that splits a string into an array of strings
 using `separator`. After splitting the string, the function logs
 messages indicating the original string (before the split), the separator used, the
 number of elements in the array, and the individual array elements.

```js
function splitString(stringToSplit, separator) {
  const arrayOfStrings = stringToSplit.split(separator);

  console.log("The original string is:", stringToSplit);
  console.log("The separator is:", separator);
  console.log(
    "The array has",
    arrayOfStrings.length,
    "elements:",
    arrayOfStrings.join(" / "),
  );
}

const tempestString = "Oh brave new world that has such people in it.";
const monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

const space = " ";
const comma = ",";

splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
```

This example produces the following output:
```

The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.

The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it.

The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
```

### Removing spaces from a string

 In the following example, `split()` looks for zero or more spaces, followed
 by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and
 the semicolon from the string. `nameList` is the array returned as a result
 of `split()`.

```js
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";

console.log(names);

const re = /\s\*(?:;|$)\s\*/;
const nameList = names.split(re);

console.log(nameList);
```

 This logs two lines; the first line logs the original string, and the second line logs
 the resulting array.
```

Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
```

### Returning a limited number of splits

 In the following example, `split()` looks for spaces in a string and returns
 the first 3 splits that it finds.

```js
const myString = "Hello World. How are you doing?";
const splits = myString.split(" ", 3);

console.log(splits); // [ "Hello", "World.", "How" ]
```

### Splitting with a `RegExp` to include parts of the separator in the result

 If `separator` is a regular expression that contains capturing
 parentheses `( )`, matched results are included in the array.

```js
const myString = "Hello 1 word. Sentence number 2.";
const splits = myString.split(/(\d)/);

console.log(splits);
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
```

**Note:** `\d` matches the character class for digits between 0 and 9.

### Using a custom splitter

An object with a `Symbol.split` method can be used as a splitter with custom behavior.

The following example splits a string using an internal state consisting of an incrementing number:

```js
const splitByNumber = {
  [Symbol.split](str) {
    let num = 1;
    let pos = 0;
    const result = [];
    while (pos < str.length) {
      const matchPos = str.indexOf(num, pos);
      if (matchPos === -1) {
        result.push(str.substring(pos));
        break;
      }
      result.push(str.substring(pos, matchPos));
      pos = matchPos + String(num).length;
      num++;
    }
    return result;
  },
};

const myString = "a1bc2c5d3e4f";
console.log(myString.split(splitByNumber)); // [ "a", "bc", "c5d", "e", "f" ]
```

The following example uses an internal state to enforce certain behavior, and to ensure a "valid" result is produced.

```js
const DELIMITER = ";";

// Split the commands, but remove any invalid or unnecessary values.
const splitCommands = {
  [Symbol.split](str, lim) {
    const results = [];
    const state = {
      on: false,
      brightness: {
        current: 2,
        min: 1,
        max: 3,
      },
    };
    let pos = 0;
    let matchPos = str.indexOf(DELIMITER, pos);

    while (matchPos !== -1) {
      const subString = str.slice(pos, matchPos).trim();

      switch (subString) {
        case "light on":
          // If the `on` state is already true, do nothing.
          if (!state.on) {
            state.on = true;
            results.push(subString);
          }
          break;

        case "light off":
          // If the `on` state is already false, do nothing.
          if (state.on) {
            state.on = false;
            results.push(subString);
          }
          break;

        case "brightness up":
          // Enforce a brightness maximum.
          if (state.brightness.current < state.brightness.max) {
            state.brightness.current += 1;
            results.push(subString);
          }
          break;

        case "brightness down":
          // Enforce a brightness minimum.
          if (state.brightness.current > state.brightness.min) {
            state.brightness.current -= 1;
            results.push(subString);
          }
          break;
      }

      if (results.length === lim) {
        break;
      }

      pos = matchPos + DELIMITER.length;
      matchPos = str.indexOf(DELIMITER, pos);
    }

    // If we broke early due to reaching the split `lim`, don't add the remaining commands.
    if (results.length < lim) {
      results.push(str.slice(pos).trim());
    }

    return results;
  },
};

const commands =
  "light on; brightness up; brightness up; brightness up; light on; brightness down; brightness down; light off";
console.log(commands.split(splitCommands, 3)); // ["light on", "brightness up", "brightness down"]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.split |

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

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

See also
--------

* Polyfill of `String.prototype.split` in `core-js` with fixes and implementation of modern behavior like `Symbol.split` support
* `String.prototype.charAt()`
* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`
* `Array.prototype.join()`
* Regular expressions guide


String.prototype.charAt() - JavaScript

String.prototype.charAt()
=========================

The **`charAt()`** method of `String` values returns a new string consisting of the single UTF-16 code unit at the given index.

`charAt()` always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at the given index, use `String.prototype.codePointAt()` and `String.fromCodePoint()`.

Try it
------

Syntax
------

```js
charAt(index)
```

### Parameters

`index`

Zero-based index of the character to be returned. Converted to an integer — `undefined` is converted to 0.

### Return value

A string representing the character (exactly one UTF-16 code unit) at the specified `index`. If `index` is out of the range of `0` – `str.length - 1`, `charAt()` returns an empty string.

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

Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character in a string called `str` is `str.length - 1`.

Unicode code points range from `0` to `1114111` (`0x10FFFF`). `charAt()` always returns a character whose value is less than `65536`, because the higher code points are represented by *a pair* of 16-bit surrogate pseudo-characters. Therefore, in order to get a full character with value greater than `65535`, it is necessary to retrieve not only `charAt(i)`, but also `charAt(i + 1)` (as if manipulating a string with two characters), or to use `codePointAt(i)` and `String.fromCodePoint()` instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

`charAt()` is very similar to using bracket notation to access a character at the specified index. The main differences are:

* `charAt()` attempts to convert `index` to an integer, while bracket notation does not, and directly uses `index` as a property name.
* `charAt()` returns an empty string if `index` is out of range, while bracket notation returns `undefined`.
Examples
--------

### Using charAt()

The following example displays characters at different locations in the string `"Brave new world"`:

```js
const anyString = "Brave new world";
console.log(`The character at index 0 is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0 is '${anyString.charAt(0)}'`);
console.log(`The character at index 1 is '${anyString.charAt(1)}'`);
console.log(`The character at index 2 is '${anyString.charAt(2)}'`);
console.log(`The character at index 3 is '${anyString.charAt(3)}'`);
console.log(`The character at index 4 is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
```

These lines display the following:
```

The character at index 0   is 'B'

The character at index 0   is 'B'
The character at index 1   is 'r'
The character at index 2   is 'a'
The character at index 3   is 'v'
The character at index 4   is 'e'
The character at index 999 is ''
```

`charAt()` may return lone surrogates, which are not valid Unicode characters.

```js
const str = "𠮷𠮾";
console.log(str.charAt(0)); // "\ud842", which is not a valid Unicode character
console.log(str.charAt(1)); // "\udfb7", which is not a valid Unicode character
```

To get the full Unicode code point at the given index, use an indexing method that splits by Unicode code points, such as `String.prototype.codePointAt()` and spreading strings into an array of Unicode code points.

```js
const str = "𠮷𠮾";
console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷"
console.log([...str][0]); // "𠮷"
```

**Note:** Avoid re-implementing the solutions above using `charAt()`. The detection of lone surrogates and their pairing is complex, and built-in APIs may be more performant as they directly use the internal representation of the string. Install a polyfill for the APIs mentioned above if necessary.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.charat |

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

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

See also
--------

* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`
* `String.prototype.charCodeAt()`
* `String.prototype.codePointAt()`
* `String.prototype.split()`
* `String.fromCodePoint()`
* JavaScript has a Unicode problem by Mathias Bynens (2013)


String.prototype.strike() - JavaScript

String.prototype.strike()
=========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`strike()`** method of `String` values creates a string that embeds this string in a `<strike>` element (`<strike>str</strike>`), which causes this string to be displayed as struck-out text.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `strike()`, the `<strike>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use the `<del>` for deleted content or the `<s>` for content that is no longer accurate or no longer relevant instead.

Syntax
------

```js
strike()
```

### Parameters

None.

### Return value

A string beginning with a `<strike>` start tag, then the text `str`, and then a `</strike>` end tag.

Examples
--------

### Using strike()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.strike();
```

This will create the following HTML:

```html
<strike>Hello, world</strike>
```

**Warning:** This markup is invalid, because `strike` is no longer a valid element.

Instead of using `strike()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("s");
elem.innerText = contentString;
document.body.appendChild(elem);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.strike |

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

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

See also
--------

* Polyfill of `String.prototype.strike` in `core-js`
* HTML wrapper methods
* `<strike>`


String.prototype.lastIndexOf() - JavaScript

String.prototype.lastIndexOf()
==============================

The **`lastIndexOf()`** method of `String` values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

Try it
------

Syntax
------

```js
lastIndexOf(searchString)
lastIndexOf(searchString, position)
```

### Parameters

`searchString`

Substring to search for. All values are coerced to strings, so omitting it or passing `undefined` causes `lastIndexOf()` to search for the string `"undefined"`, which is rarely what you want.

`position` Optional

The method returns the index of the last occurrence of the specified substring at a position less than or equal to `position`, which defaults to `+Infinity`. If `position` is greater than the length of the calling string, the method searches the entire string. If `position` is less than `0`, the behavior is the same as for `0` — that is, the method looks for the specified substring only at index `0`.

* `'hello world hello'.lastIndexOf('world', 4)` returns `-1` — because, while the substring `world` does occurs at index `6`, that position is not less than or equal to `4`.
* `'hello world hello'.lastIndexOf('hello', 99)` returns `12` — because the last occurrence of `hello` at a position less than or equal to `99` is at position `12`.
* `'hello world hello'.lastIndexOf('hello', 0)` and `'hello world hello'.lastIndexOf('hello', -5)` both return `0` — because both cause the method to only look for `hello` at index `0`.

### Return value

The index of the last occurrence of `searchString` found, or `-1` if not found.

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

Strings are zero-indexed: The index of a string's first character is `0`, and the index of a string's last character is the length of the string minus 1.

```js
"canal".lastIndexOf("a"); // returns 3
"canal".lastIndexOf("a", 2); // returns 1
"canal".lastIndexOf("a", 0); // returns -1
"canal".lastIndexOf("x"); // returns -1
"canal".lastIndexOf("c", -5); // returns 0
"canal".lastIndexOf("c", 0); // returns 0
"canal".lastIndexOf(""); // returns 5
"canal".lastIndexOf("", 2); // returns 2
```

### Case-sensitivity

 The `lastIndexOf()` method is case sensitive. For example, the following
 expression returns `-1`:

```js
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
```

Examples
--------

### Using indexOf() and lastIndexOf()

 The following example uses `indexOf()` and
 `lastIndexOf()` to locate values in the string
 `"Brave, Brave New World"`.

```js
const anyString = "Brave, Brave New World";

console.log(anyString.indexOf("Brave")); // 0
console.log(anyString.lastIndexOf("Brave")); // 7
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.lastindexof |

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

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

See also
--------

* `String.prototype.charAt()`
* `String.prototype.indexOf()`
* `String.prototype.split()`
* `Array.prototype.indexOf()`
* `Array.prototype.lastIndexOf()`


String.prototype.toLowerCase() - JavaScript

String.prototype.toLowerCase()
==============================

The **`toLowerCase()`** method of `String` values returns this string converted to lower case.

Try it
------

Syntax
------

```js
toLowerCase()
```

### Parameters

None.

### Return value

A new string representing the calling string converted to lower case.

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

 The `toLowerCase()` method returns the value of the string converted to
 lower case. `toLowerCase()` does not affect the value of the string
 `str` itself.

Examples
--------

### Using `toLowerCase()`

```js
console.log("ALPHABET".toLowerCase()); // 'alphabet'
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.tolowercase |

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

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

See also
--------

* `String.prototype.toLocaleLowerCase()`
* `String.prototype.toLocaleUpperCase()`
* `String.prototype.toUpperCase()`


String.prototype.bold() - JavaScript

String.prototype.bold()
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`bold()`** method of `String` values creates a string that embeds this string in a `<b>` element (`<b>str</b>`), which causes this string to be displayed as bold.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
bold()
```

### Parameters

None.

### Return value

A string beginning with a `<b>` start tag, then the text `str`, and then a `</b>` end tag.

Examples
--------

### Using bold()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.bold();
```

This will create the following HTML:

```html
<b>Hello, world</b>
```

Instead of using `bold()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("b");
elem.innerText = contentString;
document.body.appendChild(elem);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.bold |

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

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

See also
--------

* Polyfill of `String.prototype.bold` in `core-js`
* HTML wrapper methods
* `<b>`


String.prototype.fontsize() - JavaScript

String.prototype.fontsize()
===========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`fontsize()`** method of `String` values creates a string that embeds this string in a `<font>` element (`<font size="...">str</font>`), which causes this string to be displayed in the specified font size.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `fontsize()`, the `<font>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

Syntax
------

```js
fontsize(size)
```

### Parameters

`size`

An integer between 1 and 7, or a string representing a signed integer between 1 and 7.

### Return value

A string beginning with a `<font size="size">` start tag (double quotes in `size` are replaced with `"`), then the text `str`, and then a `</font>` end tag.

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

The `fontsize()` method itself simply joins the string parts together without any validation or normalization. However, to create valid `<font>` elements, When you specify size as an integer, you set the font size of `str` to one of the 7 defined sizes. You can specify `size` as a string such as `"-2"` or `"+3"` to adjust the font size of `str` relative to 3, the default value.

Examples
--------

### Using fontsize()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.fontsize(7);
```

This will create the following HTML:

```html
<font size="7">Hello, world</font>
```

**Warning:** This markup is invalid, because `font` is no longer a valid element.

Instead of using `fontsize()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate `font-size` through the `element.style` attribute:

```js
document.getElementById("yourElemId").style.fontSize = "7pt";
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.fontsize |

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

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

See also
--------

* Polyfill of `String.prototype.fontsize` in `core-js`
* HTML wrapper methods
* `<font>`


String.prototype.toString() - JavaScript

String.prototype.toString()
===========================

The **`toString()`** method of `String` values returns this string value.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the specified string value.

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

 The `String` object overrides the `toString` method of `Object`; it does not inherit
 `Object.prototype.toString()`. For `String` values, the `toString` method returns the string itself (if it's a primitive) or the string that the `String` object wraps. It has the exact same implementation as `String.prototype.valueOf()`.

The `toString()` method requires its `this` value to be a `String` primitive or wrapper object. It throws a `TypeError` for other `this` values without attempting to coerce them to string values.

Because `String` doesn't have a `[@@toPrimitive]()` method, JavaScript calls the `toString()` method automatically when a `String` *object* is used in a context expecting a string, such as in a template literal. However, String *primitive* values do not consult the `toString()` method to be coerced to strings — since they are already strings, no conversion is performed.

```js
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"
```

Examples
--------

### Using toString()

The following example displays the string value of a `String` object:

```js
const x = new String("Hello world");

console.log(x.toString()); // "Hello world"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.tostring |

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

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

See also
--------

* `String.prototype.valueOf()`


String.fromCodePoint() - JavaScript

String.fromCodePoint()
======================

The **`String.fromCodePoint()`** static method returns a string created from the specified sequence of code points.

Try it
------

Syntax
------

```js
String.fromCodePoint()
String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /\* …, \*/ numN)
```

### Parameters

`num1`, …, `numN`

An integer between `0` and `0x10FFFF` (inclusive) representing a Unicode code point.

### Return value

A string created by using the specified sequence of code points.

### Exceptions

`RangeError`

Thrown if `numN` is not an integer, is less than `0`, or is greater than `0x10FFFF` after being converted to a number.

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

Because `fromCodePoint()` is a static method of `String`, you always use it as `String.fromCodePoint()`, rather than as a method of a `String` value you created.

Unicode code points range from `0` to `1114111` (`0x10FFFF`). In UTF-16, each string index is a code unit with value `0` – `65535`. Higher code points are represented by *a pair* of 16-bit surrogate pseudo-characters. Therefore, `fromCodePoint()` may return a string whose `length` (in UTF-16 code units) is larger than the number of arguments passed. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Examples
--------

### Using fromCodePoint()

Valid input:

```js
String.fromCodePoint(42); // "\*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Є"
String.fromCodePoint(0x2f804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07"
```

Invalid input:

```js
String.fromCodePoint("\_"); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError
```

### Compared to fromCharCode()

`String.fromCharCode()` cannot return supplementary characters (i.e. code points `0x010000` – `0x10FFFF`) by specifying their code point. Instead, it requires the UTF-16 surrogate pair in order to return a supplementary character:

```js
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
```

`String.fromCodePoint()`, on the other hand, can return 4-byte supplementary characters, as well as the more common 2-byte BMP characters, by specifying their code point (which is equivalent to the UTF-32 code unit):

```js
String.fromCodePoint(0x1f303); // or 127747 in decimal
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.fromcodepoint |

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

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

See also
--------

* Polyfill of `String.fromCodePoint` in `core-js`
* `String.fromCharCode()`
* `String.prototype.charAt()`
* `String.prototype.codePointAt()`
* `String.prototype.charCodeAt()`


String.prototype.italics() - JavaScript

String.prototype.italics()
==========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`italics()`** method of `String` values creates a string that embeds this string in an `<i>` element (`<i>str</i>`), which causes this string to be displayed as italic.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
italics()
```

### Parameters

None.

### Return value

A string beginning with an `<i>` start tag, then the text `str`, and then an `</i>` end tag.

Examples
--------

### Using italics()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.italics();
```

This will create the following HTML:

```html
<i>Hello, world</i>
```

Instead of using `italics()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("i");
elem.innerText = contentString;
document.body.appendChild(elem);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.italics |

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

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

See also
--------

* Polyfill of `String.prototype.italics` in `core-js`
* HTML wrapper methods
* `<i>`


String.prototype.concat() - JavaScript

String.prototype.concat()
=========================

 The **`concat()`** method of `String` values concatenates
 the string arguments to this string and returns a new string.

Try it
------

Syntax
------

```js
concat()
concat(str1)
concat(str1, str2)
concat(str1, str2, /\* …, \*/ strN)
```

### Parameters

`str1`, …, `strN`

One or more strings to concatenate to `str`.

### Return value

A new string containing the combined text of the strings provided.

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

 The `concat()` function concatenates the string arguments to the calling
 string and returns a new string. Changes to the original string or the returned string
 don't affect the other.

 If the arguments are not of the type string, they are converted to string values before
 concatenating.

The `concat()` method is very similar to the addition/string concatenation operators (`+`, `+=`), except that `concat()` coerces its arguments directly to strings, while addition coerces its operands to primitives first. For more information, see the reference page for the `+` operator.

Examples
--------

### Using concat()

The following example combines strings into a new string.

```js
const hello = "Hello, ";
console.log(hello.concat("Kevin", ". Have a nice day."));
// Hello, Kevin. Have a nice day.

const greetList = ["Hello", " ", "Venkat", "!"];
"".concat(...greetList); // "Hello Venkat!"

"".concat({}); // "[object Object]"
"".concat([]); // ""
"".concat(null); // "null"
"".concat(true); // "true"
"".concat(4, 5); // "45"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.concat |

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

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

See also
--------

* `Array.prototype.concat()`
* Addition (`+`)


String.prototype.substr() - JavaScript

String.prototype.substr()
=========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`substr()`** method of `String` values returns a portion of this string, starting at the specified index and extending for a given number of characters afterwards.

**Note:** `substr()` is not part of the main ECMAScript specification — it's defined in Annex B: Additional ECMAScript Features for Web Browsers, which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard `String.prototype.substring()` and `String.prototype.slice()` methods instead to make their code maximally cross-platform friendly. The `String.prototype.substring()` page has some comparisons between the three methods.

Try it
------

Syntax
------

```js
substr(start)
substr(start, length)
```

### Parameters

`start`

The index of the first character to include in the returned substring.

`length` Optional

The number of characters to extract.

### Return value

A new string containing the specified part of the given string.

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

A string's `substr()` method extracts `length` characters from the string, counting from the `start` index.

* If `start >= str.length`, an empty string is returned.
* If `start < 0`, the index starts counting from the end of the string. More formally, in this case the substring starts at `max(start + str.length, 0)`.
* If `start` is omitted or `undefined`, it's treated as `0`.
* If `length` is omitted or `undefined`, or if `start + length >= str.length`, `substr()` extracts characters to the end of the string.
* If `length < 0`, an empty string is returned.
* For both `start` and `length`, `NaN` is treated as `0`.

Although you are encouraged to avoid using `substr()`, there is no trivial way to migrate `substr()` to either `slice()` or `substring()` in legacy code without essentially writing a polyfill for `substr()`. For example, `str.substr(a, l)`, `str.slice(a, a + l)`, and `str.substring(a, a + l)` all have different results when `str = "01234", a = 1, l = -2` — `substr()` returns an empty string, `slice()` returns `"123"`, while `substring()` returns `"0"`. The actual refactoring path depends on the knowledge of the range of `a` and `l`.

Examples
--------

### Using substr()

```js
const aString = "Mozilla";

console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.substr |

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

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

See also
--------

* Polyfill of `String.prototype.substr` in `core-js`
* `String.prototype.slice()`
* `String.prototype.substring()`


String.prototype.matchAll() - JavaScript

String.prototype.matchAll()
===========================

The **`matchAll()`** method of `String` values returns an iterator of all results matching this string against a regular expression, including capturing groups.

Try it
------

Syntax
------

```js
matchAll(regexp)
```

### Parameters

`regexp`

A regular expression object, or any object that has a `Symbol.matchAll` method.

If `regexp` is not a `RegExp` object and does not have a `Symbol.matchAll` method, it is implicitly converted to a `RegExp` by using `new RegExp(regexp, 'g')`.

If `regexp` is a regex, then it must have the global (`g`) flag set, or a `TypeError` is thrown.

### Return value

An iterable iterator object (which is not restartable) of matches or an empty iterator if no matches are found. Each value yielded by the iterator is an array with the same shape as the return value of `RegExp.prototype.exec()`.

### Exceptions

`TypeError`

Thrown if the `regexp` is a regex that does not have the global (`g`) flag set (its `flags` property does not contain `"g"`).

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

The implementation of `String.prototype.matchAll` itself is very simple — it simply calls the `Symbol.matchAll` method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes from `RegExp.prototype[@@matchAll]()`.

Examples
--------

### Regexp.prototype.exec() and matchAll()

Without `matchAll()`, it's possible to use calls to `regexp.exec()` (and regexes with the `g` flag) in a loop to obtain all the matches:

```js
const regexp = /foo[a-z]\*/g;
const str = "table football, foosball";
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(
    `Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,
  );
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
```

With `matchAll()` available, you can avoid the `while` loop and `exec` with `g`. Instead, you get an iterator to use with the more convenient `for...of`, array spreading, or `Array.from()` constructs:

```js
const regexp = /foo[a-z]\*/g;
const str = "table football, foosball";
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(
    `Found ${match[0]} start=${match.index} end=${
 match.index + match[0].length
 }.`,
  );
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.

// matches iterator is exhausted after the for...of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), (m) => m[0]);
// [ "football", "foosball" ]
```

`matchAll` will throw an exception if the `g` flag is missing.

```js
const regexp = /[a-c]/;
const str = "abc";
str.matchAll(regexp);
// TypeError
```

`matchAll` internally makes a clone of the `regexp` — so, unlike `regexp.exec()`, `lastIndex` does not change as the string is scanned.

```js
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
```

However, this means that unlike using `regexp.exec()` in a loop, you can't mutate `lastIndex` to make the regex advance or rewind.

### Better access to capturing groups (than String.prototype.match())

Another compelling reason for `matchAll` is the improved access to capture groups.

Capture groups are ignored when using `match()` with the global `g` flag:

```js
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";

str.match(regexp); // ['test1', 'test2']
```

Using `matchAll`, you can access capture groups easily:

```js
const array = [...str.matchAll(regexp)];

array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]
```

### Using matchAll() with a non-RegExp implementing @@matchAll

If an object has a `Symbol.matchAll` method, it can be used as a custom matcher. The return value of `Symbol.matchAll` becomes the return value of `matchAll()`.

```js
const str = "Hmm, this is interesting.";

str.matchAll({
  [Symbol.matchAll](str) {
    return [["Yes, it's interesting."]];
  },
}); // returns [["Yes, it's interesting."]]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.matchall |

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

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

See also
--------

* Polyfill of `String.prototype.matchAll` in `core-js`
* `String.prototype.match()`
* Regular expressions guide
* Groups and backreferences guide
* `RegExp`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `RegExp.prototype[@@matchAll]()`