repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/blink/index.md | ---
title: String.prototype.blink()
slug: Web/JavaScript/Reference/Global_Objects/String/blink
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.blink
---
{{JSRef}} {{Deprecated_Header}}
The **`blink()`** method of {{jsxref("String")}} values creates a string that embeds this string in a `<blink>` element (`<blink>str</blink>`), which used to cause a string to blink in old browsers.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `blink()`, the `<blink>` element itself is removed from modern browsers, and blinking text is frowned upon by several accessibility standards. Avoid using the element in any way.
## Syntax
```js-nolint
blink()
```
### Parameters
None.
### Return value
A string beginning with a `<blink>` start tag, then the text `str`, and then a `</blink>` end tag.
## Examples
### Using blink()
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.blink();
```
This will create the following HTML:
```html
<blink>Hello, world</blink>
```
> **Warning:** This markup is invalid, because `blink` is no longer a valid element.
You should avoid blinking elements altogether.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.blink` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/anchor/index.md | ---
title: String.prototype.anchor()
slug: Web/JavaScript/Reference/Global_Objects/String/anchor
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.anchor
---
{{JSRef}} {{Deprecated_Header}}
The **`anchor()`** method of {{jsxref("String")}} values creates a string that embeds this string in an {{HTMLElement("a")}} element with a name (`<a name="...">str</a>`).
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
>
> The HTML specification no longer allows the {{HTMLElement("a")}} element to have a `name` attribute, so this method doesn't even create valid markup.
## Syntax
```js-nolint
anchor(name)
```
### Parameters
- `name`
- : A string representing a `name` value to put into the generated `<a name="...">` start tag.
### Return value
A string beginning with an `<a name="name">` start tag (double quotes in `name` are replaced with `"`), then the text `str`, and then an `</a>` end tag.
## Examples
### Using anchor()
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.anchor("hello");
```
This will create the following HTML:
```html
<a name="hello">Hello, world</a>
```
> **Warning:** This markup is invalid, because `name` is no longer a valid attribute of the {{HTMLElement("a")}} element.
Instead of using `anchor()` and creating HTML text directly, you should use DOM APIs such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("a");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.anchor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("a")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/tolocaleuppercase/index.md | ---
title: String.prototype.toLocaleUpperCase()
slug: Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toLocaleUpperCase
---
{{JSRef}}
The **`toLocaleUpperCase()`** method of {{jsxref("String")}} values returns this string converted to upper case, according to any locale-specific case mappings.
{{EmbedInteractiveExample("pages/js/string-tolocaleuppercase.html")}}
## Syntax
```js-nolint
toLocaleUpperCase()
toLocaleUpperCase(locales)
```
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
Unlike other methods that use the `locales` argument, `toLocaleUpperCase()` does not allow locale matching. Therefore, after checking the validity of the `locales` argument, `toLocaleUpperCase()` always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.
### Return value
A new string representing the calling string converted to upper case, according to any
locale-specific case mappings.
## Description
The `toLocaleUpperCase()` method returns the value of the string converted
to upper case according to any locale-specific case mappings.
`toLocaleUpperCase()` does not affect the value of the string itself. In most
cases, this will produce the same result as {{jsxref("String/toUpperCase", "toUpperCase()")}}, but for some locales, such as Turkish, whose case mappings do not
follow the default case mappings in Unicode, there may be a different result.
Also notice that conversion is not necessarily a 1:1 character mapping, as some
characters might result in two (or even more) characters when transformed to upper-case.
Therefore the length of the result string can differ from the input length. This also
implies that the conversion is not stable, so i.E. the following can return
`false`:
`x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()`
## Examples
### Using toLocaleUpperCase()
```js
"alphabet".toLocaleUpperCase(); // 'ALPHABET'
"Gesäß".toLocaleUpperCase(); // 'GESÄSS'
"i\u0307".toLocaleUpperCase("lt-LT"); // 'I'
const locales = ["lt", "LT", "lt-LT", "lt-u-co-phonebk", "lt-x-lietuva"];
"i\u0307".toLocaleUpperCase(locales); // 'I'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.toLocaleLowerCase()")}}
- {{jsxref("String.prototype.toLowerCase()")}}
- {{jsxref("String.prototype.toUpperCase()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/raw/index.md | ---
title: String.raw()
slug: Web/JavaScript/Reference/Global_Objects/String/raw
page-type: javascript-static-method
browser-compat: javascript.builtins.String.raw
---
{{JSRef}}
The **`String.raw()`** static method is a tag function of [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals). This is similar to the `r` prefix in Python, or the `@` prefix in C# for string literals. It's used to get the raw string form of template literals — that is, substitutions (e.g. `${foo}`) are processed, but escape sequences (e.g. `\n`) are not.
{{EmbedInteractiveExample("pages/js/string-raw.html")}}
## Syntax
```js-nolint
String.raw(strings)
String.raw(strings, sub1)
String.raw(strings, sub1, sub2)
String.raw(strings, sub1, sub2, /* …, */ subN)
String.raw`templateString`
```
### Parameters
- `strings`
- : Well-formed template literal array object, like `{ raw: ['foo', 'bar', 'baz'] }`. Should be an object with a `raw` property whose value is an array-like object of strings.
- `sub1`, …, `subN`
- : Contains substitution values.
- `templateString`
- : A [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals), optionally with substitutions (`${...}`).
### Return value
The raw string form of a given template literal.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the first argument doesn't have a `raw` property, or the `raw` property is `undefined` or `null`.
## Description
In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other [tag functions](/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)).
`String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code.
> **Warning:** You should not use `String.raw` directly as an "identity" tag. See [Building an identity tag](#building_an_identity_tag) for how to implement this.
If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings.
## Examples
### Using String.raw()
```js
String.raw`Hi\n${2 + 3}!`;
// 'Hi\\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
String.raw`Hi\u000A!`;
// 'Hi\\u000A!', same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.
const name = "Bob";
String.raw`Hi\n${name}!`;
// 'Hi\\nBob!', substitutions are processed.
String.raw`Hi \${name}!`;
// 'Hi \\${name}!', the dollar sign is escaped; there's no interpolation.
```
### Building an identity tag
Many tools give special treatment to literals tagged by a particular name.
```js-nolint
// Some formatters will format this literal's content as HTML
const doc = html`<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
`;
```
One might naïvely implement the `html` tag as:
```js
const html = String.raw;
```
This, in fact, works for the case above. However, because `String.raw` would concatenate the _raw_ string literals instead of the "cooked" ones, escape sequences would not be processed.
```js-nolint
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\\n</canvas>"
```
This may not be what you want for a "true identity" tag, where the tag is purely for markup and doesn't change the literal's value. In this case, you can create a custom tag and pass the "cooked" (i.e. escape sequences are processed) literal array to `String.raw`, pretending they are raw strings.
```js-nolint
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\n</canvas>"; the "\n" becomes a line break
```
Notice the first argument is an object with a `raw` property, whose value is an array-like object (with a `length` property and integer indexes) representing the separated strings in the template literal. The rest of the arguments are the substitutions. Since the `raw` value can be any array-like object, it can even be a string! For example, `'test'` is treated as `['t', 'e', 's', 't']`. The following is equivalent to `` `t${0}e${1}s${2}t` ``:
```js
String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.raw` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals)
- {{jsxref("String")}}
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/substr/index.md | ---
title: String.prototype.substr()
slug: Web/JavaScript/Reference/Global_Objects/String/substr
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.substr
---
{{JSRef}} {{Deprecated_Header}}
The **`substr()`** method of {{jsxref("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](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html), which is normative optional for non-browser runtimes. Therefore, people are advised to use the standard [`String.prototype.substring()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) and [`String.prototype.slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) methods instead to make their code maximally cross-platform friendly. The [`String.prototype.substring()` page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr) has some comparisons between the three methods.
{{EmbedInteractiveExample("pages/js/string-substr.html")}}
## Syntax
```js-nolint
substr(start)
substr(start, length)
```
### Parameters
- `start`
- : The index of the first character to include in the returned substring.
- `length` {{optional_inline}}
- : 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 {{jsxref("undefined")}}, it's treated as `0`.
- If `length` is omitted or {{jsxref("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`, {{jsxref("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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.substr` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.slice()")}}
- {{jsxref("String.prototype.substring()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/trim/index.md | ---
title: String.prototype.trim()
slug: Web/JavaScript/Reference/Global_Objects/String/trim
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.trim
---
{{JSRef}}
The **`trim()`** method of {{jsxref("String")}} values removes whitespace from both ends of this string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use {{jsxref("String/trimStart", "trimStart()")}} or {{jsxref("String/trimEnd", "trimEnd()")}}.
{{EmbedInteractiveExample("pages/js/string-trim.html")}}
## Syntax
```js-nolint
trim()
```
### Parameters
None.
### Return value
A new string representing `str` stripped of whitespace from both its beginning and end. Whitespace is defined as [white space](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators).
If neither the beginning or end of `str` has any whitespace, a new string is still returned (essentially a copy of `str`).
## Examples
### Using trim()
The following example trims whitespace from both ends of `str`.
```js
const str = " foo ";
console.log(str.trim()); // 'foo'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.trimStart()")}}
- {{jsxref("String.prototype.trimEnd()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/padstart/index.md | ---
title: String.prototype.padStart()
slug: Web/JavaScript/Reference/Global_Objects/String/padStart
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.padStart
---
{{JSRef}}
The **`padStart()`** method of {{jsxref("String")}} values pads this string with another string (multiple times, if needed) until the resulting
string reaches the given length. The padding is applied from the start of this string.
{{EmbedInteractiveExample("pages/js/string-padstart.html")}}
## Syntax
```js-nolint
padStart(targetLength)
padStart(targetLength, padString)
```
### Parameters
- `targetLength`
- : The length of the resulting string once the current `str` has
been padded. If the value is less than or equal to `str.length`, then
`str` is returned as-is.
- `padString` {{optional_inline}}
- : The string to pad the current `str` with. If
`padString` is too long to stay within the
`targetLength`, it will be truncated from the end.
The default value is the unicode "space" character (U+0020).
### Return value
A {{jsxref("String")}} of the specified `targetLength` with
`padString` applied from the start.
## Examples
### Basic examples
```js
"abc".padStart(10); // " abc"
"abc".padStart(10, "foo"); // "foofoofabc"
"abc".padStart(6, "123465"); // "123abc"
"abc".padStart(8, "0"); // "00000abc"
"abc".padStart(1); // "abc"
```
### Fixed width string number conversion
```js
// JavaScript version of: (unsigned)
// printf "%0*d" width num
function leftFillNum(num, targetLength) {
return num.toString().padStart(targetLength, "0");
}
const num = 123;
console.log(leftFillNum(num, 5)); // "00123"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.padStart` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.padEnd()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/touppercase/index.md | ---
title: String.prototype.toUpperCase()
slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toUpperCase
---
{{JSRef}}
The **`toUpperCase()`** method of {{jsxref("String")}} values returns this string converted to uppercase.
{{EmbedInteractiveExample("pages/js/string-touppercase.html", "shorter")}}
## Syntax
```js-nolint
toUpperCase()
```
### Parameters
None.
### Return value
A new string representing the calling string converted to upper case.
## Description
The `toUpperCase()` method returns the value of the string converted to
uppercase. This method does not affect the value of the string itself since JavaScript
strings are immutable.
## Examples
### Basic usage
```js
console.log("alphabet".toUpperCase()); // 'ALPHABET'
```
### Conversion of non-string `this` values to strings
This method will convert any non-string value to a string, when you set its
`this` to a value that is not a string:
```js
const a = String.prototype.toUpperCase.call({
toString() {
return "abcdef";
},
});
const b = String.prototype.toUpperCase.call(true);
// prints out 'ABCDEF TRUE'.
console.log(a, b);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.toLocaleLowerCase()")}}
- {{jsxref("String.prototype.toLocaleUpperCase()")}}
- {{jsxref("String.prototype.toLowerCase()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/trimend/index.md | ---
title: String.prototype.trimEnd()
slug: Web/JavaScript/Reference/Global_Objects/String/trimEnd
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.trimEnd
---
{{JSRef}}
The **`trimEnd()`** method of {{jsxref("String")}} values removes whitespace from the end of this string and returns a new string, without modifying the original string. `trimRight()` is an alias of this method.
{{EmbedInteractiveExample("pages/js/string-trimend.html")}}
## Syntax
```js-nolint
trimEnd()
trimRight()
```
### Parameters
None.
### Return value
A new string representing `str` stripped of whitespace from its end (right side). Whitespace is defined as [white space](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators).
If the end of `str` has no whitespace, a new string is still returned (essentially a copy of `str`).
### Aliasing
After {{jsxref("String/trim", "trim()")}} was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with {{jsxref("String/padEnd", "padEnd()")}}, when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means:
```js
String.prototype.trimRight.name === "trimEnd";
```
## Examples
### Using trimEnd()
The following example trims whitespace from the end of `str`, but not from its start.
```js
let str = " foo ";
console.log(str.length); // 8
str = str.trimEnd();
console.log(str.length); // 6
console.log(str); // ' foo'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.trimEnd` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.trim()")}}
- {{jsxref("String.prototype.trimStart()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/strike/index.md | ---
title: String.prototype.strike()
slug: Web/JavaScript/Reference/Global_Objects/String/strike
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.strike
---
{{JSRef}} {{Deprecated_Header}}
The **`strike()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("strike")}} element (`<strike>str</strike>`), which causes this string to be displayed as struck-out text.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#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 {{HTMLElement("del")}} for deleted content or the {{HTMLElement("s")}} for content that is no longer accurate or no longer relevant instead.
## Syntax
```js-nolint
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()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("s");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.strike` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("strike")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/iswellformed/index.md | ---
title: String.prototype.isWellFormed()
slug: Web/JavaScript/Reference/Global_Objects/String/isWellFormed
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.isWellFormed
---
{{JSRef}}
The **`isWellFormed()`** method of {{jsxref("String")}} values returns a boolean indicating whether this string contains any [lone surrogates](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
## Syntax
```js-nolint
isWellFormed()
```
### Parameters
None.
### Return value
Returns `true` if this string does not contain any lone surrogates, `false` otherwise.
## Description
Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of _surrogate pairs_, which is introduced in detail in the [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) section.
`isWellFormed()` allows you to test whether a string is well-formed (i.e. does not contain any lone surrogates). Compared to a custom implementation, `isWellFormed()` is more efficient, as engines can directly access the internal representation of strings. If you need to convert a string to a well-formed string, use the {{jsxref("String/toWellFormed", "toWellFormed()")}} method. `isWellFormed()` allows you to handle ill-formed strings differently from well-formed strings, such as throwing an error or marking it as invalid.
## Examples
### Using isWellFormed()
```js
const strings = [
// Lone leading surrogate
"ab\uD800",
"ab\uD800c",
// Lone trailing surrogate
"\uDFFFab",
"c\uDFFFab",
// Well-formed
"abc",
"ab\uD83D\uDE04c",
];
for (const str of strings) {
console.log(str.isWellFormed());
}
// Logs:
// false
// false
// false
// false
// true
// true
```
### Avoiding errors in encodeURI()
{{jsxref("encodeURI")}} throws an error if the string passed is not well-formed. This can be avoided by using `isWellFormed()` to test the string before passing it to `encodeURI()`.
```js
const illFormed = "https://example.com/search?q=\uD800";
try {
encodeURI(illFormed);
} catch (e) {
console.log(e); // URIError: URI malformed
}
if (illFormed.isWellFormed()) {
console.log(encodeURI(illFormed));
} else {
console.warn("Ill-formed strings encountered."); // Ill-formed strings encountered.
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.isWellFormed` in `core-js`](https://github.com/zloirock/core-js#well-formed-unicode-strings)
- {{jsxref("String.prototype.toWellFormed()")}}
- {{jsxref("String.prototype.normalize()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/link/index.md | ---
title: String.prototype.link()
slug: Web/JavaScript/Reference/Global_Objects/String/link
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.link
---
{{JSRef}} {{Deprecated_Header}}
The **`link()`** method of {{jsxref("String")}} values creates a string that embeds this string in an {{HTMLElement("a")}} element (`<a href="...">str</a>`), to be used as a hypertext link to another URL.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
link(url)
```
### Parameters
- `url`
- : Any string that specifies the `href` attribute of the `<a>` element; it should be a valid URL (relative or absolute), with any `&` characters escaped as `&`.
### Return value
A string beginning with an `<a href="url">` start tag (double quotes in `url` are replaced with `"`), then the text `str`, and then an `</a>` end tag.
## Examples
### Using link()
The code below creates an HTML string and then replaces the document's body with it:
```js
const contentString = "MDN Web Docs";
document.body.innerHTML = contentString.link("https://developer.mozilla.org/");
```
This will create the following HTML:
```html
<a href="https://developer.mozilla.org/">MDN Web Docs</a>
```
Instead of using `link()` and creating HTML text directly, you should use DOM APIs such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "MDN Web Docs";
const elem = document.createElement("a");
elem.href = "https://developer.mozilla.org/";
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.link` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("a")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/lastindexof/index.md | ---
title: String.prototype.lastIndexOf()
slug: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.lastIndexOf
---
{{JSRef}}
The **`lastIndexOf()`** method of {{jsxref("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.
{{EmbedInteractiveExample("pages/js/string-lastindexof.html")}}
## Syntax
```js-nolint
lastIndexOf(searchString)
lastIndexOf(searchString, position)
```
### Parameters
- `searchString`
- : Substring to search for. All values are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `lastIndexOf()` to search for the string `"undefined"`, which is rarely what you want.
- `position` {{optional_inline}}
- : 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 {{jsxref("String/indexOf", "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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.split()")}}
- {{jsxref("Array.prototype.indexOf()")}}
- {{jsxref("Array.prototype.lastIndexOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/concat/index.md | ---
title: String.prototype.concat()
slug: Web/JavaScript/Reference/Global_Objects/String/concat
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.concat
---
{{JSRef}}
The **`concat()`** method of {{jsxref("String")}} values concatenates
the string arguments to this string and returns a new string.
{{EmbedInteractiveExample("pages/js/string-concat.html")}}
## Syntax
```js-nolint
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](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) (`+`, `+=`), except that `concat()` [coerces its arguments directly to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition).
## 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Array.prototype.concat()")}}
- [Addition (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/localecompare/index.md | ---
title: String.prototype.localeCompare()
slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.localeCompare
---
{{JSRef}}
The **`localeCompare()`** method of {{jsxref("String")}} values returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order. In implementations with [`Intl.Collator` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) support, this method simply calls `Intl.Collator`.
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an {{jsxref("Intl.Collator")}} object and use the function provided by its {{jsxref("Intl/Collator/compare", "compare()")}} method.
{{EmbedInteractiveExample("pages/js/string-localecompare.html")}}
## Syntax
```js-nolint
localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)
```
### Parameters
The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the [`Intl.Collator` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), these parameters correspond exactly to the [`Intl.Collator()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) constructor's parameters. Implementations without `Intl.Collator` support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be _consistent_.
- `compareString`
- : The string against which the `referenceStr` is compared. All values are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `localeCompare()` to compare against the string `"undefined"`, which is rarely what you want.
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) parameter of the `Intl.Collator()` constructor.
In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used.
- `options` {{optional_inline}}
- : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) parameter of the `Intl.Collator()` constructor.
In implementations without `Intl.Collator` support, this parameter is ignored.
See the [`Intl.Collator()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator) for details on the `locales` and `options` parameters and how to use them.
### Return value
A **negative** number if `referenceStr` occurs before `compareString`; **positive** if the `referenceStr` occurs after `compareString`; `0` if they are equivalent.
In implementations with `Intl.Collator`, this is equivalent to `new Intl.Collator(locales, options).compare(referenceStr, compareString)`.
## Description
Returns an integer indicating whether the `referenceStr` comes
before, after or is equivalent to the `compareString`.
- Negative when the `referenceStr` occurs before
`compareString`
- Positive when the `referenceStr` occurs after
`compareString`
- Returns `0` if they are equivalent
> **Warning:** Do not rely on exact return values of `-1` or `1`!
>
> Negative and positive integer results vary between browsers (as well as between
> browser versions) because the ECMAScript specification only mandates negative and positive
> values. Some browsers may return `-2` or `2`, or even some other
> negative or positive value.
## Examples
### Using localeCompare()
```js
// The letter "a" is before "c" yielding a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)
// Alphabetically the word "check" comes after "against" yielding a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)
// "a" and "a" are equivalent yielding a neutral value of zero
"a".localeCompare("a"); // 0
```
### Sort an array
`localeCompare()` enables case-insensitive sorting for an array.
```js
const items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"];
items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']
```
### Check browser support for extended arguments
The `locales` and `options` arguments are
not supported in all browsers yet.
To check whether an implementation supports them, use the `"i"` argument (a
requirement that illegal language tags are rejected) and look for a
{{jsxref("RangeError")}} exception:
```js
function localeCompareSupportsLocales() {
try {
"foo".localeCompare("bar", "i");
} catch (e) {
return e.name === "RangeError";
}
return false;
}
```
### Using locales
The results provided by `localeCompare()` vary between languages. In order
to get the sort order of the language used in the user interface of your application,
make sure to specify that language (and possibly some fallback languages) using the
`locales` argument:
```js
console.log("ä".localeCompare("z", "de")); // a negative value: in German, ä sorts before z
console.log("ä".localeCompare("z", "sv")); // a positive value: in Swedish, ä sorts after z
```
### Using options
The results provided by `localeCompare()` can be customized using the
`options` argument:
```js
// in German, ä has a as the base letter
console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0
// in Swedish, ä and a are separate base letters
console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value
```
### Numeric sorting
```js
// by default, "2" > "10"
console.log("2".localeCompare("10")); // 1
// numeric using options:
console.log("2".localeCompare("10", undefined, { numeric: true })); // -1
// numeric using locales tag:
console.log("2".localeCompare("10", "en-u-kn-true")); // -1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Intl.Collator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/italics/index.md | ---
title: String.prototype.italics()
slug: Web/JavaScript/Reference/Global_Objects/String/italics
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.italics
---
{{JSRef}} {{Deprecated_Header}}
The **`italics()`** method of {{jsxref("String")}} values creates a string that embeds this string in an {{HTMLElement("i")}} element (`<i>str</i>`), which causes this string to be displayed as italic.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
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()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("i");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.italics` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("i")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/replace/index.md | ---
title: String.prototype.replace()
slug: Web/JavaScript/Reference/Global_Objects/String/replace
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.replace
---
{{JSRef}}
The **`replace()`** method of {{jsxref("String")}} values returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a {{jsxref("RegExp")}}, and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged.
{{EmbedInteractiveExample("pages/js/string-replace.html")}}
## Syntax
```js-nolint
replace(pattern, replacement)
```
### Parameters
- `pattern`
- : Can be a string or an object with a [`Symbol.replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) method — the typical example being a [regular expression](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string.
- `replacement`
- : Can be a string or a function.
- If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the [Specifying a string as the replacement](#specifying_a_string_as_the_replacement) section below.
- If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the [Specifying a function as the replacement](#specifying_a_function_as_the_replacement) section below.
### Return value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.
## Description
This method does not mutate the string value it's called on. It returns a new string.
A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use [`replaceAll()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) instead.
If `pattern` is an object with a [`Symbol.replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by [`RegExp.prototype[@@replace]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace).
If the `pattern` is an empty string, the replacement is prepended to the start of the string.
```js
"xxx".replace("", "_"); // "_xxx"
```
A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the [sticky](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replace()`, see [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace).
### Specifying a string as the replacement
The replacement string can include the following special replacement patterns:
| Pattern | Inserts |
| --------- | ---------------------------------------------------------------------------------------------- |
| `$$` | Inserts a `"$"`. |
| `$&` | Inserts the matched substring. |
| `` $` `` | Inserts the portion of the string that precedes the matched substring. |
| `$'` | Inserts the portion of the string that follows the matched substring. |
| `$n` | Inserts the `n`th (`1`-indexed) capturing group where `n` is a positive integer less than 100. |
| `$<Name>` | Inserts the named capturing group where `Name` is the group name. |
`$n` and `$<Name>` are only available if the `pattern` argument is a {{jsxref("RegExp")}} object. If the `pattern` is a string, or if the corresponding capturing group isn't present in the regex, then the pattern will be replaced as a literal. If the group is present but isn't matched (because it's part of a disjunction), it will be replaced with an empty string.
```js
"foo".replace(/(f)/, "$2");
// "$2oo"; the regex doesn't have the second group
"foo".replace("f", "$1");
// "$1oo"; the pattern is a string, so it doesn't have any groups
"foo".replace(/(f)|(g)/, "$2");
// "oo"; the second group exists but isn't matched
```
### Specifying a function as the replacement
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.
> **Note:** The above-mentioned special replacement patterns do _not_ apply for strings returned from the replacer function.
The function has the following signature:
```js
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
return replacement;
}
```
The arguments to the function are as follows:
- `match`
- : The matched substring. (Corresponds to `$&` above.)
- `p1, p2, …, pN`
- : The `n`th string found by a capture group (including named capturing groups), provided the first argument to `replace()` is a {{jsxref("RegExp")}} object. (Corresponds to `$1`, `$2`, etc. above.) For example, if the `pattern` is `/(\a+)(\b+)/`, then `p1` is the match for `\a+`, and `p2` is the match for `\b+`. If the group is part of a disjunction (e.g. `"abc".replace(/(a)|(b)/, replacer)`), the unmatched alternative will be `undefined`.
- `offset`
- : The offset of the matched substring within the whole string being examined. For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be `1`.
- `string`
- : The whole string being examined.
- `groups`
- : An object whose keys are the used group names, and whose values are the matched portions (`undefined` if not matched). Only present if the `pattern` contains at least one named capturing group.
The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object — and, if so, how many capture groups it has.
The following example will set `newString` to `'abc - 12345 - #$*%'`:
```js
function replacer(match, p1, p2, p3, offset, string) {
// p1 is non-digits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(" - ");
}
const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
```
The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
## Examples
### Defining the regular expression in replace()
In the following example, the regular expression is defined in `replace()` and includes the ignore case flag.
```js
const str = "Twas the night before Xmas...";
const newstr = str.replace(/xmas/i, "Christmas");
console.log(newstr); // Twas the night before Christmas...
```
This logs `'Twas the night before Christmas...'`.
> **Note:** See [the regular expression guide](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) for more explanations about regular expressions.
### Using the global and ignoreCase flags with replace()
Global replace can only be done with a regular expression. In the following example, the regular expression includes the [global and ignore case flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) which permits `replace()` to replace each occurrence of `'apples'` in the string with `'oranges'`.
```js
const re = /apples/gi;
const str = "Apples are round, and apples are juicy.";
const newstr = str.replace(re, "oranges");
console.log(newstr); // oranges are round, and oranges are juicy.
```
This logs `'oranges are round, and oranges are juicy'`.
### Switching words in a string
The following script switches the words in the string. For the replacement text, the script uses [capturing groups](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) and the `$1` and `$2` replacement patterns.
```js
const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newstr = str.replace(re, "$2, $1");
console.log(newstr); // Cruz, Maria
```
This logs `'Cruz, Maria'`.
### Using an inline function that modifies the matched characters
In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.
The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.
```js
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? "-" : "") + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
```
Given `styleHyphenFormat('borderTop')`, this returns `'border-top'`.
Because we want to further transform the _result_ of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the [`toLowerCase()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) method. If we had tried to do this using the match without a function, the {{jsxref("String/toLowerCase", "toLowerCase()")}} would have no effect.
```js example-bad
// Won't work
const newString = propertyName.replace(/[A-Z]/g, "-" + "$&".toLowerCase());
```
This is because `'$&'.toLowerCase()` would first be evaluated as a string literal (resulting in the same `'$&'`) before using the characters as a pattern.
### Replacing a Fahrenheit degree with its Celsius equivalent
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with `"F"`. The function returns the Celsius number ending with `"C"`. For example, if the input number is `"212F"`, the function returns `"100C"`. If the number is `"0F"`, the function returns `"-17.77777777777778C"`.
The regular expression `test` checks for any number that ends with `F`. The number of Fahrenheit degrees is accessible to the function through its second parameter, `p1`. The function sets the Celsius number based on the number of Fahrenheit degrees passed in a string to the `f2c()` function. `f2c()` then returns the Celsius number. This function approximates Perl's `s///e` flag.
```js
function f2c(x) {
function convert(str, p1, offset, s) {
return `${((p1 - 32) * 5) / 9}C`;
}
const s = String(x);
const test = /(-?\d+(?:\.\d*)?)F\b/g;
return s.replace(test, convert);
}
```
### Making a generic replacer
Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives the `offset` parameter, it will be trivial if the regex is statically known.
```js
"abcd".replace(/(bc)/, (match, p1, offset) => `${match} (${offset}) `);
// "abc (1) d"
```
However, this replacer would be hard to generalize if we want it to work with any regex pattern. The replacer is _variadic_ — the number of arguments it receives depends on the number of capturing groups present. We can use [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), but it would also collect `offset`, `string`, etc. into the array. The fact that `groups` may or may not be passed depending on the identity of the regex would also make it hard to generically know which argument corresponds to the `offset`.
```js example-bad
function addOffset(match, ...args) {
const offset = args.at(-2);
return `${match} (${offset}) `;
}
console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (abcd) d"
```
The `addOffset` example above doesn't work when the regex contains a named group, because in this case `args.at(-2)` would be the `string` instead of the `offset`.
Instead, you need to extract the last few arguments based on type, because `groups` is an object while `string` is a string.
```js
function addOffset(match, ...args) {
const hasNamedGroups = typeof args.at(-1) === "object";
const offset = hasNamedGroups ? args.at(-3) : args.at(-2);
return `${match} (${offset}) `;
}
console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (1) d"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.replace` in `core-js` with fixes and implementation of modern behavior like `Symbol.replace` support](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.replaceAll()")}}
- {{jsxref("String.prototype.match()")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
- [`Symbol.replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace)
- [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/trimstart/index.md | ---
title: String.prototype.trimStart()
slug: Web/JavaScript/Reference/Global_Objects/String/trimStart
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.trimStart
---
{{JSRef}}
The **`trimStart()`** method of {{jsxref("String")}} values removes whitespace from the beginning of this string and returns a new string, without modifying the original string. `trimLeft()` is an alias of this method.
{{EmbedInteractiveExample("pages/js/string-trimstart.html")}}
## Syntax
```js-nolint
trimStart()
trimLeft()
```
### Parameters
None.
### Return value
A new string representing `str` stripped of whitespace from its beginning (left side). Whitespace is defined as [white space](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) characters plus [line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators).
If the beginning of `str` has no whitespace, a new string is still returned (essentially a copy of `str`).
### Aliasing
After {{jsxref("String/trim", "trim()")}} was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with {{jsxref("String/padStart", "padStart()")}}, when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means:
```js
String.prototype.trimLeft.name === "trimStart";
```
## Examples
### Using trimStart()
The following example trims whitespace from the start of `str`, but not from its end.
```js
let str = " foo ";
console.log(str.length); // 8
str = str.trimStart();
console.log(str.length); // 5
console.log(str); // 'foo '
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.trimStart` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.trim()")}}
- {{jsxref("String.prototype.trimEnd()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/fromcharcode/index.md | ---
title: String.fromCharCode()
slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode
page-type: javascript-static-method
browser-compat: javascript.builtins.String.fromCharCode
---
{{JSRef}}
The **`String.fromCharCode()`** static method returns a string created from the specified sequence of UTF-16 code units.
{{EmbedInteractiveExample("pages/js/string-fromcharcode.html", "shorter")}}
## Syntax
```js-nolint
String.fromCharCode()
String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /* …, */ numN)
```
### Parameters
- `num1`, …, `numN`
- : A number between `0` and `65535` (`0xFFFF`) representing a UTF-16 code unit. Numbers greater than `0xFFFF` are truncated to the last 16 bits. No validity checks are performed.
### Return value
A string of length `N` consisting of the `N` specified UTF-16 code units.
## Description
Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` value you created.
Unicode code points range from `0` to `1114111` (`0x10FFFF`). `charCodeAt()` always returns a value that is less than `65536`, because the higher code points are represented by _a pair_ of 16-bit surrogate pseudo-characters. Therefore, in order to produce a full character with value greater than `65535`, it is necessary to provide two code units (as if manipulating a string with two characters). For information on Unicode, see [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
Because `fromCharCode()` only works with 16-bit values (same as the `\u` escape sequence), a surrogate pair is required in order to return a supplementary character. For example, both `String.fromCharCode(0xd83c, 0xdf03)` and `"\ud83c\udf03"` return code point `U+1F303` "Night with Stars". While there is a mathematical relationship between the supplementary code point value (e.g. `0x1f303`) and both surrogate values that represent it (e.g., `0xd83c` and `0xdf03`), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. For this reason, it's more convenient to use {{jsxref("String.fromCodePoint()")}}, which allows for returning supplementary characters based on their actual code point value. For example, `String.fromCodePoint(0x1f303)` returns code point `U+1F303` "Night with Stars".
## Examples
### Using fromCharCode()
BMP characters, in UTF-16, use a single code unit:
```js
String.fromCharCode(65, 66, 67); // returns "ABC"
String.fromCharCode(0x2014); // returns "—"
String.fromCharCode(0x12014); // also returns "—"; the digit 1 is truncated and ignored
String.fromCharCode(8212); // also returns "—"; 8212 is the decimal form of 0x2014
```
Supplementary characters, in UTF-16, require two code units (i.e. a surrogate pair):
```js
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
String.fromCharCode(0xd834, 0xdf06, 0x61, 0xd834, 0xdf07); // "\uD834\uDF06a\uD834\uDF07"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.fromCodePoint()")}}
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.prototype.charCodeAt()")}}
- {{jsxref("String.prototype.codePointAt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/fixed/index.md | ---
title: String.prototype.fixed()
slug: Web/JavaScript/Reference/Global_Objects/String/fixed
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.fixed
---
{{JSRef}} {{Deprecated_Header}}
The **`fixed()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("tt")}} element (`<tt>str</tt>`), which causes this string to be displayed in a fixed-width font.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#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](/en-US/docs/Web/CSS) properties instead.
## Syntax
```js-nolint
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 {{cssxref("font-family")}} through the {{domxref("HTMLElement/style", "element.style")}} attribute:
```js
document.getElementById("yourElemId").style.fontFamily = "monospace";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.fixed` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("tt")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/@@iterator/index.md | ---
title: String.prototype[@@iterator]()
slug: Web/JavaScript/Reference/Global_Objects/String/@@iterator
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.@@iterator
---
{{JSRef}}
The **`[@@iterator]()`** method of {{jsxref("String")}} values implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows strings to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns a [string iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the Unicode code points of the string value as individual strings.
{{EmbedInteractiveExample("pages/js/string-prototype-@@iterator.html")}}
## Syntax
```js-nolint
string[Symbol.iterator]()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the Unicode code points of the string value as individual strings.
## Description
Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved.
```js
// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji
// "Family: Man, Boy"
[..."👨👦"]; // [ '👨', '', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ
```
## Examples
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes strings [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.
```js
const str = "A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A";
for (const v of str) {
console.log(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"
```
### 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 str = "A\uD835\uDC68";
const strIter = str[Symbol.iterator]();
console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype[@@iterator]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting) guide
- {{jsxref("Symbol.iterator")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/sub/index.md | ---
title: String.prototype.sub()
slug: Web/JavaScript/Reference/Global_Objects/String/sub
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.sub
---
{{JSRef}} {{Deprecated_Header}}
The **`sub()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("sub")}} element (`<sub>str</sub>`), which causes this string to be displayed as subscript.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
sub()
```
### Parameters
None.
### Return value
A string beginning with a `<sub>` start tag, then the text `str`, and then a `</sub>` end tag.
## Examples
### Using sub()
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.sub();
```
This will create the following HTML:
```html
<sub>Hello, world</sub>
```
Instead of using `sub()` and creating HTML text directly, you should use DOM APIs such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("sub");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.sub` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("sub")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/bold/index.md | ---
title: String.prototype.bold()
slug: Web/JavaScript/Reference/Global_Objects/String/bold
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.bold
---
{{JSRef}} {{Deprecated_Header}}
The **`bold()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("b")}} element (`<b>str</b>`), which causes this string to be displayed as bold.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
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()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("b");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.bold` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("b")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/tolowercase/index.md | ---
title: String.prototype.toLowerCase()
slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.toLowerCase
---
{{JSRef}}
The **`toLowerCase()`** method of {{jsxref("String")}} values returns this string converted to lower case.
{{EmbedInteractiveExample("pages/js/string-tolowercase.html", "shorter")}}
## Syntax
```js-nolint
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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.toLocaleLowerCase()")}}
- {{jsxref("String.prototype.toLocaleUpperCase()")}}
- {{jsxref("String.prototype.toUpperCase()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/normalize/index.md | ---
title: String.prototype.normalize()
slug: Web/JavaScript/Reference/Global_Objects/String/normalize
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.normalize
---
{{JSRef}}
The **`normalize()`** method of {{jsxref("String")}} values returns the Unicode Normalization
Form of this string.
{{EmbedInteractiveExample("pages/js/string-normalize.html", "taller")}}
## Syntax
```js-nolint
normalize()
normalize(form)
```
### Parameters
- `form` {{optional_inline}}
- : One of `"NFC"`, `"NFD"`, `"NFKC"`, or
`"NFKD"`, specifying the Unicode Normalization Form. If omitted or
{{jsxref("undefined")}}, `"NFC"` is used.
These values have the following meanings:
- `"NFC"`
- : Canonical Decomposition, followed by Canonical Composition.
- `"NFD"`
- : Canonical Decomposition.
- `"NFKC"`
- : Compatibility Decomposition, followed by Canonical Composition.
- `"NFKD"`
- : Compatibility Decomposition.
### Return value
A string containing the Unicode Normalization Form of the given string.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `form` isn't one of the values
specified above.
## Description
Unicode assigns a unique numerical value, called a _code point_, to each
character. For example, the code point for `"A"` is given as U+0041. However,
sometimes more than one code point, or sequence of code points, can represent the same
abstract character — the character `"ñ"` for example can be represented by
either of:
- The single code point U+00F1.
- The code point for `"n"` (U+006E) followed by the code point for the
combining tilde (U+0303).
```js
const string1 = "\u00F1";
const string2 = "\u006E\u0303";
console.log(string1); // ñ
console.log(string2); // ñ
```
However, since the code points are different, string comparison will not treat them as
equal. And since the number of code points in each version is different, they even have
different lengths.
```js
const string1 = "\u00F1"; // ñ
const string2 = "\u006E\u0303"; // ñ
console.log(string1 === string2); // false
console.log(string1.length); // 1
console.log(string2.length); // 2
```
The `normalize()` method helps solve this problem by converting a string
into a normalized form common for all sequences of code points that represent the same
characters. There are two main normalization forms, one based on **canonical
equivalence** and the other based on **compatibility**.
### Canonical equivalence normalization
In Unicode, two sequences of code points have canonical equivalence if they represent
the same abstract characters, and should always have the same visual appearance and
behavior (for example, they should always be sorted in the same way).
You can use `normalize()` using the `"NFD"` or `"NFC"`
arguments to produce a form of the string that will be the same for all canonically
equivalent strings. In the example below we normalize two representations of the
character `"ñ"`:
```js
let string1 = "\u00F1"; // ñ
let string2 = "\u006E\u0303"; // ñ
string1 = string1.normalize("NFD");
string2 = string2.normalize("NFD");
console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2
```
#### Composed and decomposed forms
Note that the length of the normalized form under `"NFD"` is
`2`. That's because `"NFD"` gives you the
**decomposed** version of the canonical form, in which single code points
are split into multiple combining ones. The decomposed canonical form for
`"ñ"` is `"\u006E\u0303"`.
You can specify `"NFC"` to get the **composed** canonical form,
in which multiple code points are replaced with single code points where possible. The
composed canonical form for `"ñ"` is `"\u00F1"`:
```js
let string1 = "\u00F1"; // ñ
let string2 = "\u006E\u0303"; // ñ
string1 = string1.normalize("NFC");
string2 = string2.normalize("NFC");
console.log(string1 === string2); // true
console.log(string1.length); // 1
console.log(string2.length); // 1
console.log(string2.codePointAt(0).toString(16)); // f1
```
### Compatibility normalization
In Unicode, two sequences of code points are compatible if they represent the same
abstract characters, and should be treated alike in some — but not necessarily all —
applications.
All canonically equivalent sequences are also compatible, but not vice versa.
For example:
- the code point U+FB00 represents the [ligature](/en-US/docs/Glossary/Ligature) `"ff"`. It is compatible
with two consecutive U+0066 code points (`"ff"`).
- the code point U+24B9 represents the symbol
`"Ⓓ"`.
It is compatible with the U+0044 code point (`"D"`).
In some respects (such as sorting) they should be treated as equivalent—and in some
(such as visual appearance) they should not, so they are not canonically equivalent.
You can use `normalize()` using the `"NFKD"` or
`"NFKC"` arguments to produce a form of the string that will be the same for
all compatible strings:
```js
let string1 = "\uFB00";
let string2 = "\u0066\u0066";
console.log(string1); // ff
console.log(string2); // ff
console.log(string1 === string2); // false
console.log(string1.length); // 1
console.log(string2.length); // 2
string1 = string1.normalize("NFKD");
string2 = string2.normalize("NFKD");
console.log(string1); // ff <- visual appearance changed
console.log(string2); // ff
console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2
```
When applying compatibility normalization it's important to consider what you intend to
do with the strings, since the normalized form may not be appropriate for all
applications. In the example above the normalization is appropriate for search, because
it enables a user to find the string by searching for `"f"`. But it may not
be appropriate for display, because the visual representation is different.
As with canonical normalization, you can ask for decomposed or composed compatible
forms by passing `"NFKD"` or `"NFKC"`, respectively.
## Examples
### Using normalize()
```js
// Initial string
// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
const str = "\u1E9B\u0323";
// Canonically-composed form (NFC)
// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
str.normalize("NFC"); // '\u1E9B\u0323'
str.normalize(); // same as above
// Canonically-decomposed form (NFD)
// U+017F: LATIN SMALL LETTER LONG S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFD"); // '\u017F\u0323\u0307'
// Compatibly-composed (NFKC)
// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
str.normalize("NFKC"); // '\u1E69'
// Compatibly-decomposed (NFKD)
// U+0073: LATIN SMALL LETTER S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFKD"); // '\u0073\u0323\u0307'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Unicode Standard Annex #15, Unicode Normalization Forms](https://www.unicode.org/reports/tr15/)
- [Unicode equivalence](https://en.wikipedia.org/wiki/Unicode_equivalence) on Wikipedia
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/valueof/index.md | ---
title: String.prototype.valueOf()
slug: Web/JavaScript/Reference/Global_Objects/String/valueOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.valueOf
---
{{JSRef}}
The **`valueOf()`** method of {{jsxref("String")}} values returns this string value.
{{EmbedInteractiveExample("pages/js/string-valueof.html")}}
## Syntax
```js-nolint
valueOf()
```
### Parameters
None.
### Return value
A string representing the primitive value of a given {{jsxref("String")}} object.
## Description
The `valueOf()` method of {{jsxref("String")}} returns the primitive value
of a {{jsxref("String")}} object as a string data type. This value is equivalent to
{{jsxref("String.prototype.toString()")}}.
This method is usually called internally by JavaScript and not explicitly in code.
## Examples
### Using `valueOf()`
```js
const x = new String("Hello world");
console.log(x.valueOf()); // 'Hello world'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.toString()")}}
- {{jsxref("Object.prototype.valueOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/charat/index.md | ---
title: String.prototype.charAt()
slug: Web/JavaScript/Reference/Global_Objects/String/charAt
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.charAt
---
{{JSRef}}
The **`charAt()`** method of {{jsxref("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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters), so it may return lone surrogates. To get the full Unicode code point at the given index, use {{jsxref("String.prototype.codePointAt()")}} and {{jsxref("String.fromCodePoint()")}}.
{{EmbedInteractiveExample("pages/js/string-charat.html", "shorter")}}
## Syntax
```js-nolint
charAt(index)
```
### Parameters
- `index`
- : Zero-based index of the character to be returned. [Converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) — `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 {{jsxref("String/codePointAt", "codePointAt(i)")}} and {{jsxref("String.fromCodePoint()")}} instead. For information on Unicode, see [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
`charAt()` is very similar to using [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#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:
```plain
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 {{jsxref("String.prototype.codePointAt()")}} and [spreading strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) 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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.indexOf()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
- {{jsxref("String.prototype.charCodeAt()")}}
- {{jsxref("String.prototype.codePointAt()")}}
- {{jsxref("String.prototype.split()")}}
- {{jsxref("String.fromCodePoint()")}}
- [JavaScript has a Unicode problem](https://mathiasbynens.be/notes/javascript-unicode) by Mathias Bynens (2013)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/charcodeat/index.md | ---
title: String.prototype.charCodeAt()
slug: Web/JavaScript/Reference/Global_Objects/String/charCodeAt
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.charCodeAt
---
{{JSRef}}
The **`charCodeAt()`** method of {{jsxref("String")}} values returns an integer between `0` and `65535` representing the UTF-16 code unit at the given index.
`charCodeAt()` always indexes the string as a sequence of [UTF-16 code units](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters), so it may return lone surrogates. To get the full Unicode code point at the given index, use {{jsxref("String.prototype.codePointAt()")}}.
{{EmbedInteractiveExample("pages/js/string-charcodeat.html", "shorter")}}
## Syntax
```js-nolint
charCodeAt(index)
```
### Parameters
- `index`
- : Zero-based index of the character to be returned. [Converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) — `undefined` is converted to 0.
### Return value
An integer between `0` and `65535` representing the UTF-16 code unit value of the character at the specified `index`. If `index` is out of range of `0` – `str.length - 1`, `charCodeAt()` returns {{jsxref("NaN")}}.
## 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`). `charCodeAt()` always returns a value that 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 `charCodeAt(i)`, but also `charCodeAt(i + 1)` (as if manipulating a string with two characters), or to use {{jsxref("String/codePointAt", "codePointAt(i)")}} instead. For information on Unicode, see [UTF-16 characters, Unicode code points, and grapheme clusters](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters).
## Examples
### Using charCodeAt()
The following example returns `65`, the Unicode value for A.
```js
"ABC".charCodeAt(0); // returns 65
```
`charCodeAt()` may return lone surrogates, which are not valid Unicode characters.
```js
const str = "𠮷𠮾";
console.log(str.charCodeAt(0)); // 55362, or d842, which is not a valid Unicode character
console.log(str.charCodeAt(1)); // 57271, or dfb7, which is not a valid Unicode character
```
To get the full Unicode code point at the given index, use {{jsxref("String.prototype.codePointAt()")}}.
```js
const str = "𠮷𠮾";
console.log(str.codePointAt(0)); // 134071
```
> **Note:** Avoid re-implementing `codePointAt()` using `charCodeAt()`. The translation from UTF-16 surrogates to Unicode code points is complex, and `codePointAt()` may be more performant as it directly uses the internal representation of the string. Install a polyfill for `codePointAt()` if necessary.
Below is a possible algorithm to convert a pair of UTF-16 code units into a Unicode code point, adapted from the [Unicode FAQ](https://unicode.org/faq/utf_bom.html#utf16-3):
```js
// constants
const LEAD_OFFSET = 0xd800 - (0x10000 >> 10);
const SURROGATE_OFFSET = 0x10000 - (0xd800 << 10) - 0xdc00;
function utf16ToUnicode(lead, trail) {
return (lead << 10) + trail + SURROGATE_OFFSET;
}
function unicodeToUTF16(codePoint) {
const lead = LEAD_OFFSET + (codePoint >> 10);
const trail = 0xdc00 + (codePoint & 0x3ff);
return [lead, trail];
}
const str = "𠮷";
console.log(utf16ToUnicode(str.charCodeAt(0), str.charCodeAt(1))); // 134071
console.log(str.codePointAt(0)); // 134071
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.fromCharCode()")}}
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.fromCodePoint()")}}
- {{jsxref("String.prototype.codePointAt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/string/index.md | ---
title: String() constructor
slug: Web/JavaScript/Reference/Global_Objects/String/String
page-type: javascript-constructor
browser-compat: javascript.builtins.String.String
---
{{JSRef}}
The **`String()`** constructor creates {{jsxref("String")}} objects. When called as a function, it returns primitive values of type String.
## Syntax
```js-nolint
new String(thing)
String(thing)
```
> **Note:** `String()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but with different effects. See [Return value](#return_value).
### Parameters
- `thing`
- : Anything to be converted to a string.
### Return value
When `String` is called as a constructor (with `new`), it creates a {{jsxref("String")}} object, which is **not** a primitive.
When `String` is called as a function, it coerces the parameter to a string primitive. [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) values would be converted to `"Symbol(description)"`, where `description` is the [description](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description) of the Symbol, instead of throwing.
> **Warning:** You should rarely find yourself using `String` as a constructor.
## Examples
### String constructor and String function
String function and String constructor produce different results:
```js
const a = new String("Hello world"); // a === "Hello world" is false
const b = String("Hello world"); // b === "Hello world" is true
a instanceof String; // is true
b instanceof String; // is false
typeof a; // "object"
typeof b; // "string"
```
Here, the function produces a string (the {{Glossary("primitive")}} type) as promised.
However, the constructor produces an instance of the type String (an object wrapper) and
that's why you rarely want to use the String constructor at all.
### Using String() to stringify a symbol
`String()` is the only case where a symbol can be converted to a string without throwing, because it's very explicit.
```js example-bad
const sym = Symbol("example");
`${sym}`; // TypeError: Cannot convert a Symbol value to a string
"" + sym; // TypeError: Cannot convert a Symbol value to a string
"".concat(sym); // TypeError: Cannot convert a Symbol value to a string
```
```js example-good
const sym = Symbol("example");
String(sym); // "Symbol(example)"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/replaceall/index.md | ---
title: String.prototype.replaceAll()
slug: Web/JavaScript/Reference/Global_Objects/String/replaceAll
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.replaceAll
---
{{JSRef}}
The **`replaceAll()`** method of {{jsxref("String")}} values returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a {{jsxref("RegExp")}}, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged.
{{EmbedInteractiveExample("pages/js/string-replaceall.html")}}
## Syntax
```js-nolint
replaceAll(pattern, replacement)
```
### Parameters
- `pattern`
- : Can be a string or an object with a [`Symbol.replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) method — the typical example being a [regular expression](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). Any value that doesn't have the `Symbol.replace` method will be coerced to a string.
If `pattern` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes), then it must have the global (`g`) flag set, or a {{jsxref("TypeError")}} is thrown.
- `replacement`
- : Can be a string or a function. The replacement has the same semantics as that of [`String.prototype.replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace).
### Return value
A new string, with all matches of a pattern replaced by a replacement.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `pattern` [is a regex](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#special_handling_for_regexes) that does not have the global (`g`) flag set (its [`flags`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags) property does not contain `"g"`).
## Description
This method does not mutate the string value it's called on. It returns a new string.
Unlike [`replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the [`RegExp()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) constructor without escaping special characters may unintentionally change its semantics.
```js
function unsafeRedactName(text, name) {
return text.replace(new RegExp(name, "g"), "[REDACTED]");
}
function safeRedactName(text, name) {
return text.replaceAll(name, "[REDACTED]");
}
const report =
"A hacker called ha.*er used special characters in their name to breach the system.";
console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system."
console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
```
If `pattern` is an object with a [`Symbol.replace`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `@@replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global).
If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to [`split()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) behavior.
```js
"xxx".replaceAll("", "_"); // "_x_x_x_"
```
For more information about how regex properties (especially the [sticky](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) flag) interact with `replaceAll()`, see [`RegExp.prototype[@@replace]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace).
## Examples
### Using replaceAll()
```js
"aabbcc".replaceAll("b", ".");
// 'aa..cc'
```
### Non-global regex throws
When using a regular expression search value, it must be global. This won't work:
```js example-bad
"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp
```
This will work:
```js example-good
"aabbcc".replaceAll(/b/g, ".");
("aa..cc");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.replaceAll` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("String.prototype.replace()")}}
- {{jsxref("String.prototype.match()")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/indexof/index.md | ---
title: String.prototype.indexOf()
slug: Web/JavaScript/Reference/Global_Objects/String/indexOf
page-type: javascript-instance-method
browser-compat: javascript.builtins.String.indexOf
---
{{JSRef}}
The **`indexOf()`** method of {{jsxref("String")}} values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
{{EmbedInteractiveExample("pages/js/string-indexof.html", "taller")}}
## Syntax
```js-nolint
indexOf(searchString)
indexOf(searchString, position)
```
### Parameters
- `searchString`
- : Substring to search for. All values are [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), so omitting it or passing `undefined` causes `indexOf()` to search for the string `"undefined"`, which is rarely what you want.
- `position` {{optional_inline}}
- : The method returns the index of the first occurrence of the specified substring at a position greater than or equal to `position`, which defaults to `0`. If `position` is greater than the length of the calling string, the method doesn't search the calling string at all. If `position` is less than zero, the method behaves as it would if `position` were `0`.
- `'hello world hello'.indexOf('o', -5)` returns `4` — because it causes the method to behave as if the second argument were `0`, and the first occurrence of `o` at a position greater or equal to `0` is at position `4`.
- `'hello world hello'.indexOf('world', 12)` returns `-1` — because, while it's true the substring `world` occurs at index `6`, that position is not greater than or equal to `12`.
- `'hello world hello'.indexOf('o', 99)` returns `-1` — because `99` is greater than the length of `hello world hello`, which causes the method to not search the string at all.
### Return value
The index of the first occurrence of `searchString` found, or `-1` if not found.
#### Return value when using an empty search string
Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string's length, the return value is the same as the value of the second argument:
```js
"hello world".indexOf(""); // returns 0
"hello world".indexOf("", 0); // returns 0
"hello world".indexOf("", 3); // returns 3
"hello world".indexOf("", 8); // returns 8
```
However, with a second argument whose value is greater than or equal to the string's length, the return value is the string's length:
```js
"hello world".indexOf("", 11); // returns 11
"hello world".indexOf("", 13); // returns 11
"hello world".indexOf("", 22); // returns 11
```
In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.
## 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
"Blue Whale".indexOf("Blue"); // returns 0
"Blue Whale".indexOf("Blute"); // returns -1
"Blue Whale".indexOf("Whale", 0); // returns 5
"Blue Whale".indexOf("Whale", 5); // returns 5
"Blue Whale".indexOf("Whale", 7); // returns -1
"Blue Whale".indexOf(""); // returns 0
"Blue Whale".indexOf("", 9); // returns 9
"Blue Whale".indexOf("", 10); // returns 10
"Blue Whale".indexOf("", 11); // returns 10
```
The `indexOf()` method is case sensitive. For example, the following
expression returns `-1`:
```js
"Blue Whale".indexOf("blue"); // returns -1
```
### Checking occurrences
When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is `-1`:
```js
"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale'
"Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale'
```
## Examples
### Using indexOf()
The following example uses `indexOf()` to locate substrings in the string
`"Brave new world"`.
```js
const str = "Brave new world";
console.log(str.indexOf("w")); // 8
console.log(str.indexOf("new")); // 6
```
### indexOf() and case-sensitivity
The following example defines two string variables.
The variables contain the same string, except that the second string contains uppercase
letters. The first {{domxref("console/log_static", "console.log()")}} method displays `19`. But
because the `indexOf()` method is case sensitive, the string
`"cheddar"` is not found in `myCapString`, so the second
`console.log()` method displays `-1`.
```js
const myString = "brie, pepper jack, cheddar";
const myCapString = "Brie, Pepper Jack, Cheddar";
console.log(myString.indexOf("cheddar")); // 19
console.log(myCapString.indexOf("cheddar")); // -1
```
### Using indexOf() to count occurrences of a letter in a string
The following example sets `count` to the number of occurrences of the
letter `e` in the string `str`:
```js
const str = "To be, or not to be, that is the question.";
let count = 0;
let position = str.indexOf("e");
while (position !== -1) {
count++;
position = str.indexOf("e", position + 1);
}
console.log(count); // 4
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.charAt()")}}
- {{jsxref("String.prototype.lastIndexOf()")}}
- {{jsxref("String.prototype.includes()")}}
- {{jsxref("String.prototype.split()")}}
- {{jsxref("Array.prototype.indexOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/sup/index.md | ---
title: String.prototype.sup()
slug: Web/JavaScript/Reference/Global_Objects/String/sup
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.sup
---
{{JSRef}} {{Deprecated_Header}}
The **`sup()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("sup")}} element (`<sup>str</sup>`), which causes this string to be displayed as superscript.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
sup()
```
### Parameters
None.
### Return value
A string beginning with a `<sup>` start tag, then the text `str`, and then a `</sup>` end tag.
## Examples
### Using sup()
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.sup();
```
This will create the following HTML:
```html
<sup>Hello, world</sup>
```
Instead of using `sup()` and creating HTML text directly, you should use DOM APIs such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("sup");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.sup` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("sup")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/small/index.md | ---
title: String.prototype.small()
slug: Web/JavaScript/Reference/Global_Objects/String/small
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.small
---
{{JSRef}} {{Deprecated_Header}}
The **`small()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("small")}} element (`<small>str</small>`), which causes this string to be displayed in a small font.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. Use [DOM APIs](/en-US/docs/Web/API/Document_Object_Model) such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) instead.
## Syntax
```js-nolint
small()
```
### Parameters
None.
### Return value
A string beginning with a `<small>` start tag, then the text `str`, and then a `</small>` end tag.
## Examples
### Using small()
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.small();
```
This will create the following HTML:
```html
<small>Hello, world</small>
```
Instead of using `small()` and creating HTML text directly, you should use DOM APIs such as [`document.createElement()`](/en-US/docs/Web/API/Document/createElement). For example:
```js
const contentString = "Hello, world";
const elem = document.createElement("small");
elem.innerText = contentString;
document.body.appendChild(elem);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.small` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("small")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/fontcolor/index.md | ---
title: String.prototype.fontcolor()
slug: Web/JavaScript/Reference/Global_Objects/String/fontcolor
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.fontcolor
---
{{JSRef}} {{Deprecated_Header}}
The **`fontcolor()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("font")}} element (`<font color="...">str</font>`), which causes this string to be displayed in the specified font color.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `fontcolor()`, the `<font>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use [CSS](/en-US/docs/Web/CSS) properties instead.
## Syntax
```js-nolint
fontcolor(color)
```
### Parameters
- `color`
- : A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the [CSS color reference](/en-US/docs/Web/CSS/color_value).
### Return value
A string beginning with a `<font color="color">` start tag (double quotes in `color` are replaced with `"`), then the text `str`, and then a `</font>` end tag.
## Description
The `fontcolor()` method itself simply joins the string parts together without any validation or normalization. However, to create valid {{HTMLElement("font")}} elements, if you express color as a hexadecimal RGB triplet, you must use the format `rrggbb`. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is `"FA8072"`.
## Examples
### Using fontcolor()
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.fontcolor("red");
```
This will create the following HTML:
```html
<font color="red">Hello, world</font>
```
> **Warning:** This markup is invalid, because `font` is no longer a valid element.
Instead of using `fontcolor()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate {{cssxref("color")}} through the {{domxref("HTMLElement/style", "element.style")}} attribute:
```js
document.getElementById("yourElemId").style.color = "red";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.fontcolor` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("font")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/string | data/mdn-content/files/en-us/web/javascript/reference/global_objects/string/big/index.md | ---
title: String.prototype.big()
slug: Web/JavaScript/Reference/Global_Objects/String/big
page-type: javascript-instance-method
status:
- deprecated
browser-compat: javascript.builtins.String.big
---
{{JSRef}} {{Deprecated_Header}}
The **`big()`** method of {{jsxref("String")}} values creates a string that embeds this string in a {{HTMLElement("big")}} element (`<big>str</big>`), which causes this string to be displayed in a big font.
> **Note:** All [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods) are deprecated and only standardized for compatibility purposes. For the case of `big()`, the `<big>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use [CSS](/en-US/docs/Web/CSS) properties instead.
## Syntax
```js-nolint
big()
```
### Parameters
None.
### Return value
A string beginning with a `<big>` start tag, then the text `str`, and then a `</big>` end tag.
## Examples
### Using big()
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.big();
```
This will create the following HTML:
```html
<big>Hello, world</big>
```
> **Warning:** This markup is invalid, because `big` is no longer a valid element.
Instead of using `big()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate {{cssxref("font-size")}} through the {{domxref("HTMLElement/style", "element.style")}} attribute:
```js
document.getElementById("yourElemId").style.fontSize = "2em";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `String.prototype.big` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [HTML wrapper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#html_wrapper_methods)
- {{HTMLElement("big")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asynciterator/index.md | ---
title: AsyncIterator
slug: Web/JavaScript/Reference/Global_Objects/AsyncIterator
page-type: javascript-class
browser-compat: javascript.builtins.AsyncIterator
---
{{JSRef}}
An **`AsyncIterator`** object is an object that conforms to the [async iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) by providing a `next()` method that returns a promise fulfilling to an iterator result object. The `AsyncIterator.prototype` object is a hidden global object that all built-in async iterators inherit from. It provides an [`@@asyncIterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator/@@asyncIterator) method that returns the async iterator object itself, making the async iterator also [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols).
Note that `AsyncIterator` is _not_ a global object, although it will be in the future with the [async iterator helpers proposal](https://github.com/tc39/proposal-async-iterator-helpers). The `AsyncIterator.prototype` object shared by all built-in async iterators can be obtained with the following code:
```js
const AsyncIteratorPrototype = Object.getPrototypeOf(
Object.getPrototypeOf(Object.getPrototypeOf((async function* () {})())),
);
```
## Description
Currently, the only built-in JavaScript async iterator is the {{jsxref("AsyncGenerator")}} object returned by [async generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*). There are some other built-in async iterators in web API, such as the one of a {{domxref("ReadableStream")}}.
Each of these async iterators have a distinct prototype object, which defines the `next()` method used by the particular async iterator. All of these prototype objects inherit from `AsyncIterator.prototype`, which provides am [`@@asyncIterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator) method that returns the async iterator object itself, making the async iterator also [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols).
> **Note:** `AsyncIterator.prototype` does not implement [`@@iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator), so async iterators are not [sync iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) by default.
## Instance methods
- [`AsyncIterator.prototype[@@asyncIterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator/@@asyncIterator)
- : Returns the async iterator object itself. This allows async iterator objects to also be async iterable.
## Examples
### Using an async iterator as an async iterable
All built-in async iterators are also async iterable, so you can use them in a `for await...of` loop:
```js
const asyncIterator = (async function* () {
yield 1;
yield 2;
yield 3;
})();
(async () => {
for await (const value of asyncIterator) {
console.log(value);
}
})();
// Logs: 1, 2, 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/async_function*", "async function*")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asynciterator | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asynciterator/@@asynciterator/index.md | ---
title: AsyncIterator.prototype[@@asyncIterator]()
slug: Web/JavaScript/Reference/Global_Objects/AsyncIterator/@@asyncIterator
page-type: javascript-instance-method
browser-compat: javascript.builtins.AsyncIterator.@@asyncIterator
---
{{JSRef}}
The **`[@@asyncIterator]()`** method of {{jsxref("AsyncIterator")}} instances implements the [async iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) and allows built-in async iterators to be consumed by most syntaxes expecting async iterables, such as [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loops. It returns the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), which is the async iterator object itself.
{{EmbedInteractiveExample("pages/js/map-prototype-@@iterator.html")}}
## Syntax
```js-nolint
asyncIterator[Symbol.asyncIterator]()
```
### Parameters
None.
### Return value
The value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), which is the async iterator object itself.
## Examples
### Iteration using for await...of loop
Note that you seldom need to call this method directly. The existence of the `@@asyncIterator` method makes all built-in async iterators [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), and iterating syntaxes like the `for await...of` loop automatically calls this method to obtain the async iterator to loop over.
```js
const asyncIterator = (async function* () {
yield 1;
yield 2;
yield 3;
})();
(async () => {
for await (const value of asyncIterator) {
console.log(value);
}
})();
// Logs: 1, 2, 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/unescape/index.md | ---
title: unescape()
slug: Web/JavaScript/Reference/Global_Objects/unescape
page-type: javascript-function
status:
- deprecated
browser-compat: javascript.builtins.unescape
---
{{jsSidebar("Objects")}}{{Deprecated_Header}}
> **Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use {{jsxref("decodeURIComponent()")}} or {{jsxref("decodeURI()")}} if possible.
The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like {{jsxref("escape()")}}.
## Syntax
```js-nolint
unescape(str)
```
### Parameters
- `str`
- : A string to be decoded.
### Return value
A new string in which certain characters have been unescaped.
## Description
`unescape()` is a function property of the global object.
The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is.
> **Note:** This function was used mostly for [URL encoding](https://en.wikipedia.org/wiki/URL_encoding) and is partly based on the escape format in {{rfc(1738)}}. The `unescape()` function does _not_ evaluate [escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences) in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`.
## Examples
### Using unescape()
```js
unescape("abc123"); // "abc123"
unescape("%E4%F6%FC"); // "äöü"
unescape("%u0107"); // "ć"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `unescape` in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- {{jsxref("decodeURI")}}
- {{jsxref("decodeURIComponent")}}
- {{jsxref("escape")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgeneratorfunction/index.md | ---
title: AsyncGeneratorFunction
slug: Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction
page-type: javascript-class
browser-compat: javascript.builtins.AsyncGeneratorFunction
---
{{JSRef}}
The **`AsyncGeneratorFunction`** object provides methods for [async generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*). In JavaScript, every async generator function is actually an `AsyncGeneratorFunction` object.
Note that `AsyncGeneratorFunction` is _not_ a global object. It can be obtained with the following code:
```js
const AsyncGeneratorFunction = async function* () {}.constructor;
```
`AsyncGeneratorFunction` is a subclass of {{jsxref("Function")}}.
{{EmbedInteractiveExample("pages/js/async-functionasterisk-function.html", "taller")}}
## Constructor
- {{jsxref("AsyncGeneratorFunction/AsyncGeneratorFunction", "AsyncGeneratorFunction()")}}
- : Creates a new `AsyncGeneratorFunction` object.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("Function")}}_.
These properties are defined on `AsyncGeneratorFunction.prototype` and shared by all `AsyncGeneratorFunction` instances.
- {{jsxref("Object/constructor", "AsyncGeneratorFunction.prototype.constructor")}}
- : The constructor function that created the instance object. For `AsyncGeneratorFunction` instances, the initial value is the {{jsxref("AsyncGeneratorFunction/AsyncGeneratorFunction", "AsyncGeneratorFunction")}} constructor.
- `AsyncGeneratorFunction.prototype.prototype`
- : All async generator functions share the same [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property, which is [`AsyncGenerator.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator). Each async generator function instance also has its own `prototype` property. When the async generator function is called, the returned async generator object inherits from the async generator function's `prototype` property, which in turn inherits from `AsyncGeneratorFunction.prototype.prototype`.
- `AsyncGeneratorFunction.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"AsyncGeneratorFunction"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
_Inherits instance methods from its parent {{jsxref("Function")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`async function*`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*)
- [`async function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*)
- {{jsxref("Function")}}
- {{jsxref("AsyncFunction")}}
- {{jsxref("GeneratorFunction")}}
- {{jsxref("Functions", "Functions", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgeneratorfunction | data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgeneratorfunction/asyncgeneratorfunction/index.md | ---
title: AsyncGeneratorFunction() constructor
slug: Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction/AsyncGeneratorFunction
page-type: javascript-constructor
browser-compat: javascript.builtins.AsyncGeneratorFunction.AsyncGeneratorFunction
---
{{JSRef}}
The **`AsyncGeneratorFunction()`** constructor creates {{jsxref("AsyncGeneratorFunction")}} objects.
Note that `AsyncGeneratorFunction` is not a global object. It could be obtained by evaluating the following code.
```js
const AsyncGeneratorFunction = async function* () {}.constructor;
```
The `AsyncGeneratorFunction()` constructor is not intended to be used directly, and all caveats mentioned in the {{jsxref("Function/Function", "Function()")}} description apply to `AsyncGeneratorFunction()`.
## Syntax
```js-nolint
new AsyncGeneratorFunction(functionBody)
new AsyncGeneratorFunction(arg1, functionBody)
new AsyncGeneratorFunction(arg1, arg2, functionBody)
new AsyncGeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)
AsyncGeneratorFunction(functionBody)
AsyncGeneratorFunction(arg1, functionBody)
AsyncGeneratorFunction(arg1, arg2, functionBody)
AsyncGeneratorFunction(arg1, arg2, /* …, */ argN, functionBody)
```
> **Note:** `AsyncGeneratorFunction()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `AsyncGeneratorFunction` instance.
### Parameters
See {{jsxref("Function/Function", "Function()")}}.
## Examples
### Using the constructor
The following example uses the `AsyncGeneratorFunction` constructor to create an async generator function.
```js
const AsyncGeneratorFunction = async function* () {}.constructor;
const createAsyncGenerator = new AsyncGeneratorFunction("a", "yield a * 2");
const asyncGen = createAsyncGenerator(10);
asyncGen.next().then((res) => console.log(res.value)); // 20
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`async function*`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*)
- [`async function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*)
- [`Function()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function)
- [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
- {{jsxref("Functions", "Functions", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/index.md | ---
title: Math
slug: Web/JavaScript/Reference/Global_Objects/Math
page-type: javascript-namespace
browser-compat: javascript.builtins.Math
---
{{JSRef}}
The **`Math`** namespace object contains static properties and methods for mathematical constants and functions.
`Math` works with the {{jsxref("Number")}} type. It doesn't work with {{jsxref("BigInt")}}.
## Description
Unlike most global objects, `Math` is not a constructor. You cannot use it with the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) or invoke the `Math` object as a function. All properties and methods of `Math` are static.
> **Note:** Many `Math` functions have a precision that's _implementation-dependent_.
>
> This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!
## Static properties
- {{jsxref("Math.E")}}
- : Euler's number and the base of natural logarithms; approximately `2.718`.
- {{jsxref("Math.LN10")}}
- : Natural logarithm of `10`; approximately `2.303`.
- {{jsxref("Math.LN2")}}
- : Natural logarithm of `2`; approximately `0.693`.
- {{jsxref("Math.LOG10E")}}
- : Base-10 logarithm of `E`; approximately `0.434`.
- {{jsxref("Math.LOG2E")}}
- : Base-2 logarithm of `E`; approximately `1.443`.
- {{jsxref("Math.PI")}}
- : Ratio of a circle's circumference to its diameter; approximately `3.14159`.
- {{jsxref("Math.SQRT1_2")}}
- : Square root of ½; approximately `0.707`.
- {{jsxref("Math.SQRT2")}}
- : Square root of `2`; approximately `1.414`.
- `Math[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Math"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Static methods
- {{jsxref("Math.abs()")}}
- : Returns the absolute value of `x`.
- {{jsxref("Math.acos()")}}
- : Returns the arccosine of `x`.
- {{jsxref("Math.acosh()")}}
- : Returns the hyperbolic arccosine of `x`.
- {{jsxref("Math.asin()")}}
- : Returns the arcsine of `x`.
- {{jsxref("Math.asinh()")}}
- : Returns the hyperbolic arcsine of a number.
- {{jsxref("Math.atan()")}}
- : Returns the arctangent of `x`.
- {{jsxref("Math.atan2()")}}
- : Returns the arctangent of the quotient of its arguments.
- {{jsxref("Math.atanh()")}}
- : Returns the hyperbolic arctangent of `x`.
- {{jsxref("Math.cbrt()")}}
- : Returns the cube root of `x`.
- {{jsxref("Math.ceil()")}}
- : Returns the smallest integer greater than or equal to `x`.
- {{jsxref("Math.clz32()")}}
- : Returns the number of leading zero bits of the 32-bit integer `x`.
- {{jsxref("Math.cos()")}}
- : Returns the cosine of `x`.
- {{jsxref("Math.cosh()")}}
- : Returns the hyperbolic cosine of `x`.
- {{jsxref("Math.exp()")}}
- : Returns e<sup>x</sup>, where x is the argument, and e is Euler's number (`2.718`…, the base of the natural logarithm).
- {{jsxref("Math.expm1()")}}
- : Returns subtracting `1` from `exp(x)`.
- {{jsxref("Math.floor()")}}
- : Returns the largest integer less than or equal to `x`.
- {{jsxref("Math.fround()")}}
- : Returns the nearest [single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`.
- {{jsxref("Math.hypot()")}}
- : Returns the square root of the sum of squares of its arguments.
- {{jsxref("Math.imul()")}}
- : Returns the result of the 32-bit integer multiplication of `x` and `y`.
- {{jsxref("Math.log()")}}
- : Returns the natural logarithm (㏒<sub>e</sub>; also, ㏑) of `x`.
- {{jsxref("Math.log10()")}}
- : Returns the base-10 logarithm of `x`.
- {{jsxref("Math.log1p()")}}
- : Returns the natural logarithm (㏒<sub>e</sub>; also ㏑) of `1 + x` for the number `x`.
- {{jsxref("Math.log2()")}}
- : Returns the base-2 logarithm of `x`.
- {{jsxref("Math.max()")}}
- : Returns the largest of zero or more numbers.
- {{jsxref("Math.min()")}}
- : Returns the smallest of zero or more numbers.
- {{jsxref("Math.pow()")}}
- : Returns base `x` to the exponent power `y` (that is, `x`<sup><code>y</code></sup>).
- {{jsxref("Math.random()")}}
- : Returns a pseudo-random number between `0` and `1`.
- {{jsxref("Math.round()")}}
- : Returns the value of the number `x` rounded to the nearest integer.
- {{jsxref("Math.sign()")}}
- : Returns the sign of the `x`, indicating whether `x` is positive, negative, or zero.
- {{jsxref("Math.sin()")}}
- : Returns the sine of `x`.
- {{jsxref("Math.sinh()")}}
- : Returns the hyperbolic sine of `x`.
- {{jsxref("Math.sqrt()")}}
- : Returns the positive square root of `x`.
- {{jsxref("Math.tan()")}}
- : Returns the tangent of `x`.
- {{jsxref("Math.tanh()")}}
- : Returns the hyperbolic tangent of `x`.
- {{jsxref("Math.trunc()")}}
- : Returns the integer portion of `x`, removing any fractional digits.
## Examples
### Converting between degrees and radians
The trigonometric functions `sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, and `atan2()` expect (and return) angles in _radians_.
Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:
```js
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
function radToDeg(rad) {
return rad / (Math.PI / 180);
}
```
### Calculating the height of an equilateral triangle
If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae _length of the adjacent multiplied by the tangent of the angle is equal to the opposite._

In JavaScript, we can do this with the following:
```js
50 * Math.tan(degToRad(60));
```
We use our `degToRad()` function to convert 60 degrees to radians, as {{jsxref("Math.tan()")}} expects an input value in radians.
### Returning a random integer between two bounds
This can be achieved with a combination of {{jsxref("Math.random()")}} and {{jsxref("Math.floor()")}}:
```js
function random(min, max) {
const num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
}
random(1, 10);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Number")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/cos/index.md | ---
title: Math.cos()
slug: Web/JavaScript/Reference/Global_Objects/Math/cos
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.cos
---
{{JSRef}}
The **`Math.cos()`** static method returns the cosine of a number in radians.
{{EmbedInteractiveExample("pages/js/math-cos.html")}}
## Syntax
```js-nolint
Math.cos(x)
```
### Parameters
- `x`
- : A number representing an angle in radians.
### Return value
The cosine of `x`, between -1 and 1, inclusive. If `x` is {{jsxref("Infinity")}}, `-Infinity`, or {{jsxref("NaN")}}, returns {{jsxref("NaN")}}.
## Description
Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.cos()
```js
Math.cos(-Infinity); // NaN
Math.cos(-0); // 1
Math.cos(0); // 1
Math.cos(1); // 0.5403023058681398
Math.cos(Math.PI); // -1
Math.cos(2 * Math.PI); // 1
Math.cos(Infinity); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.sin()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/imul/index.md | ---
title: Math.imul()
slug: Web/JavaScript/Reference/Global_Objects/Math/imul
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.imul
---
{{JSRef}}
The **`Math.imul()`** static method returns the result of the C-like 32-bit multiplication of the two parameters.
{{EmbedInteractiveExample("pages/js/math-imul.html")}}
## Syntax
```js-nolint
Math.imul(a, b)
```
### Parameters
- `a`
- : First number.
- `b`
- : Second number.
### Return value
The result of the C-like 32-bit multiplication of the given arguments.
## Description
`Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten).
Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. However, with [asm.js](/en-US/docs/Games/Tools/asm.js), which allows JIT-optimizers to more confidently use integers in JavaScript, multiplying two numbers stored internally as integers (which is only possible with asm.js) with `imul()` could be potentially more performant.
## Examples
### Using Math.imul()
```js
Math.imul(2, 4); // 8
Math.imul(-1, 8); // -8
Math.imul(-2, -2); // 4
Math.imul(0xffffffff, 5); // -5
Math.imul(0xfffffffe, 5); // -10
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.imul` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- [Emscripten](https://en.wikipedia.org/wiki/Emscripten) on Wikipedia
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/pow/index.md | ---
title: Math.pow()
slug: Web/JavaScript/Reference/Global_Objects/Math/pow
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.pow
---
{{JSRef}}
The **`Math.pow()`** static method returns the value of a base raised to a power. That is
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚙𝚘𝚠</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo>,</mo><mi>𝚢</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msup><mi>x</mi><mi>y</mi></msup></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.pow}(x, y)} = x^y</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-pow.html")}}
## Syntax
```js-nolint
Math.pow(base, exponent)
```
### Parameters
- `base`
- : The base number.
- `exponent`
- : The exponent number.
### Return value
A number representing `base` taken to the power of `exponent`. Returns {{jsxref("NaN")}} in one of the following cases:
- `exponent` is `NaN`.
- `base` is `NaN` and `exponent` is not `0`.
- `base` is ±1 and `exponent` is ±`Infinity`.
- `base < 0` and `exponent` is not an integer.
## Description
`Math.pow()` is equivalent to the [`**`](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) operator, except `Math.pow()` only accepts numbers.
`Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where {{jsxref("NaN")}} doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior.
Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.pow()
```js
// Simple cases
Math.pow(7, 2); // 49
Math.pow(7, 3); // 343
Math.pow(2, 10); // 1024
// Fractional exponents
Math.pow(4, 0.5); // 2 (square root of 4)
Math.pow(8, 1 / 3); // 2 (cube root of 8)
Math.pow(2, 0.5); // 1.4142135623730951 (square root of 2)
Math.pow(2, 1 / 3); // 1.2599210498948732 (cube root of 2)
// Signed exponents
Math.pow(7, -2); // 0.02040816326530612 (1/49)
Math.pow(8, -1 / 3); // 0.5
// Signed bases
Math.pow(-7, 2); // 49 (squares are positive)
Math.pow(-7, 3); // -343 (cubes can be negative)
Math.pow(-7, 0.5); // NaN (negative numbers don't have a real square root)
// Due to "even" and "odd" roots laying close to each other,
// and limits in the floating number precision,
// negative bases with fractional exponents always return NaN,
// even when the mathematical result is real
Math.pow(-7, 1 / 3); // NaN
// Zero and infinity
Math.pow(0, 0); // 1 (anything ** ±0 is 1)
Math.pow(Infinity, 0.1); // Infinity (positive exponent)
Math.pow(Infinity, -1); // 0 (negative exponent)
Math.pow(-Infinity, 1); // -Infinity (positive odd integer exponent)
Math.pow(-Infinity, 1.5); // Infinity (positive exponent)
Math.pow(-Infinity, -1); // -0 (negative odd integer exponent)
Math.pow(-Infinity, -1.5); // 0 (negative exponent)
Math.pow(0, 1); // 0 (positive exponent)
Math.pow(0, -1); // Infinity (negative exponent)
Math.pow(-0, 1); // -0 (positive odd integer exponent)
Math.pow(-0, 1.5); // 0 (positive exponent)
Math.pow(-0, -1); // -Infinity (negative odd integer exponent)
Math.pow(-0, -1.5); // Infinity (negative exponent)
Math.pow(0.9, Infinity); // 0
Math.pow(1, Infinity); // NaN
Math.pow(1.1, Infinity); // Infinity
Math.pow(0.9, -Infinity); // Infinity
Math.pow(1, -Infinity); // NaN
Math.pow(1.1, -Infinity); // 0
// NaN: only Math.pow(NaN, 0) does not result in NaN
Math.pow(NaN, 0); // 1
Math.pow(NaN, 1); // NaN
Math.pow(1, NaN); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.cbrt()")}}
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.sqrt()")}}
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/ln10/index.md | ---
title: Math.LN10
slug: Web/JavaScript/Reference/Global_Objects/Math/LN10
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.LN10
---
{{JSRef}}
The **`Math.LN10`** static data property represents the natural logarithm of 10, approximately 2.302.
{{EmbedInteractiveExample("pages/js/math-ln10.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙻𝙽𝟷𝟶</mi><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mn>10</mn><mo stretchy="false">)</mo><mo>≈</mo><mn>2.302</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.LN10
The following function returns the natural log of 10:
```js
function getNatLog10() {
return Math.LN10;
}
getNatLog10(); // 2.302585092994046
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log10()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/floor/index.md | ---
title: Math.floor()
slug: Web/JavaScript/Reference/Global_Objects/Math/floor
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.floor
---
{{JSRef}}
The **`Math.floor()`** static method always rounds down and returns the largest integer less than or equal to a given number.
{{EmbedInteractiveExample("pages/js/math-floor.html")}}
## Syntax
```js-nolint
Math.floor(x)
```
### Parameters
- `x`
- : A number.
### Return value
The largest integer smaller than or equal to `x`. It's the same value as [`-Math.ceil(-x)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil).
## Description
Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.floor()
```js
Math.floor(-Infinity); // -Infinity
Math.floor(-45.95); // -46
Math.floor(-45.05); // -46
Math.floor(-0); // -0
Math.floor(0); // 0
Math.floor(4); // 4
Math.floor(45.05); // 45
Math.floor(45.95); // 45
Math.floor(Infinity); // Infinity
```
### Decimal adjustment
In this example, we implement a method called `decimalAdjust()` that is an enhancement method of `Math.floor()`, {{jsxref("Math.ceil()")}}, and {{jsxref("Math.round()")}}. While the three `Math` functions always adjust the input to the units digit, `decimalAdjust` accepts an `exp` parameter that specifies the number of digits to the left of the decimal point to which the number should be adjusted. For example, `-1` means it would leave one digit after the decimal point (as in "× 10<sup>-1</sup>"). In addition, it allows you to select the means of adjustment — `round`, `floor`, or `ceil` — through the `type` parameter.
It does so by multiplying the number by a power of 10, then rounding the result to the nearest integer, then dividing by the power of 10. To better preserve precision, it takes advantage of Number's [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) method, which represents large or small numbers in scientific notation (like `6.02e23`).
```js
/**
* Adjusts a number to the specified digit.
*
* @param {"round" | "floor" | "ceil"} type The type of adjustment.
* @param {number} value The number.
* @param {number} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
type = String(type);
if (!["round", "floor", "ceil"].includes(type)) {
throw new TypeError(
"The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.",
);
}
exp = Number(exp);
value = Number(value);
if (exp % 1 !== 0 || Number.isNaN(value)) {
return NaN;
} else if (exp === 0) {
return Math[type](value);
}
const [magnitude, exponent = 0] = value.toString().split("e");
const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`);
// Shift back
const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
return Number(`${newMagnitude}e${+newExponent + exp}`);
}
// Decimal round
const round10 = (value, exp) => decimalAdjust("round", value, exp);
// Decimal floor
const floor10 = (value, exp) => decimalAdjust("floor", value, exp);
// Decimal ceil
const ceil10 = (value, exp) => decimalAdjust("ceil", value, exp);
// Round
round10(55.55, -1); // 55.6
round10(55.549, -1); // 55.5
round10(55, 1); // 60
round10(54.9, 1); // 50
round10(-55.55, -1); // -55.5
round10(-55.551, -1); // -55.6
round10(-55, 1); // -50
round10(-55.1, 1); // -60
// Floor
floor10(55.59, -1); // 55.5
floor10(59, 1); // 50
floor10(-55.51, -1); // -55.6
floor10(-51, 1); // -60
// Ceil
ceil10(55.51, -1); // 55.6
ceil10(51, 1); // 60
ceil10(-55.59, -1); // -55.5
ceil10(-59, 1); // -50
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.ceil()")}}
- {{jsxref("Math.round()")}}
- {{jsxref("Math.sign()")}}
- {{jsxref("Math.trunc()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/random/index.md | ---
title: Math.random()
slug: Web/JavaScript/Reference/Global_Objects/Math/random
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.random
---
{{JSRef}}
The **`Math.random()`** static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
> **Note:** `Math.random()` _does not_ provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the {{domxref("Crypto/getRandomValues", "window.crypto.getRandomValues()")}} method.
{{EmbedInteractiveExample("pages/js/math-random.html")}}
## Syntax
```js-nolint
Math.random()
```
### Parameters
None.
### Return value
A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
## Examples
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for `Math.random()` itself) aren't exact. If extremely large bounds are chosen (2<sup>53</sup> or higher), it's possible in _extremely_ rare cases to reach the usually-excluded upper bound.
### Getting a random number between 0 (inclusive) and 1 (exclusive)
```js
function getRandom() {
return Math.random();
}
```
### Getting a random number between two values
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) `min`, and is less than (and not equal) `max`.
```js
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
```
### Getting a random integer between two values
This example returns a random _integer_ between the specified values. The value is no lower than `min` (or the next integer greater than `min` if `min` isn't an integer), and is less than (but not equal to) `max`.
```js
function getRandomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // The maximum is exclusive and the minimum is inclusive
}
```
> **Note:** It might be tempting to use [`Math.round()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.
### Getting a random integer between two values, inclusive
While the `getRandomInt()` function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The `getRandomIntInclusive()` function below accomplishes that.
```js
function getRandomIntInclusive(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled); // The maximum is inclusive and the minimum is inclusive
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Crypto/getRandomValues", "window.crypto.getRandomValues()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/cosh/index.md | ---
title: Math.cosh()
slug: Web/JavaScript/Reference/Global_Objects/Math/cosh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.cosh
---
{{JSRef}}
The **`Math.cosh()`** static method returns the hyperbolic cosine of a number. That is,
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚌𝚘𝚜𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">cosh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>+</mo><msup><mi mathvariant="normal">e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow><mn>2</mn></mfrac></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.cosh}(x)} = \cosh(x) = \frac{\mathrm{e}^x + \mathrm{e}^{-x}}{2}</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-cosh.html")}}
## Syntax
```js-nolint
Math.cosh(x)
```
### Parameters
- `x`
- : A number.
### Return value
The hyperbolic cosine of `x`.
## Description
Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.cosh()
```js
Math.cosh(-Infinity); // Infinity
Math.cosh(-1); // 1.5430806348152437
Math.cosh(-0); // 1
Math.cosh(0); // 1
Math.cosh(1); // 1.5430806348152437
Math.cosh(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.cosh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.acosh()")}}
- {{jsxref("Math.asinh()")}}
- {{jsxref("Math.atanh()")}}
- {{jsxref("Math.sinh()")}}
- {{jsxref("Math.tanh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/atanh/index.md | ---
title: Math.atanh()
slug: Web/JavaScript/Reference/Global_Objects/Math/atanh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.atanh
---
{{JSRef}}
The **`Math.atanh()`** static method returns the inverse hyperbolic tangent of a number. That is,
<math display="block"><semantics><mtable columnalign="right left right left right left right left right left" columnspacing="0em" displaystyle="true"><mtr><mtd><mo>∀</mo><mi>x</mi><mo>∊</mo><mo stretchy="false">(</mo><mrow><mo>−</mo><mn>1</mn></mrow><mo>,</mo><mn>1</mn><mo stretchy="false">)</mo><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow></mtd><mtd><mo>=</mo><mo lspace="0em" rspace="0.16666666666666666em">artanh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><mo lspace="0em" rspace="0em">tanh</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mtd></mtr><mtr><mtd></mtd><mtd><mo>=</mo><mfrac><mn>1</mn><mn>2</mn></mfrac><mspace width="0.16666666666666666em"></mspace><mo lspace="0em" rspace="0em">ln</mo><mrow><mo>(</mo><mfrac><mrow><mn>1</mn><mo>+</mo><mi>x</mi></mrow><mrow><mn>1</mn><mo>−</mo><mi>x</mi></mrow></mfrac><mo>)</mo></mrow></mtd></mtr></mtable><annotation encoding="TeX">\begin{aligned}\forall x \in ({-1}, 1),\;\mathtt{\operatorname{Math.atanh}(x)} &= \operatorname{artanh}(x) = \text{the unique } y \text{ such that } \tanh(y) = x \\&= \frac{1}{2}\,\ln\left(\frac{1+x}{1-x}\right)\end{aligned}
</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-atanh.html")}}
## Syntax
```js-nolint
Math.atanh(x)
```
### Parameters
- `x`
- : A number between -1 and 1, inclusive.
### Return value
The inverse hyperbolic tangent of `x`. If `x` is 1, returns {{jsxref("Infinity")}}. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns {{jsxref("NaN")}}.
## Description
Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.atanh()
```js
Math.atanh(-2); // NaN
Math.atanh(-1); // -Infinity
Math.atanh(-0); // -0
Math.atanh(0); // 0
Math.atanh(0.5); // 0.5493061443340548
Math.atanh(1); // Infinity
Math.atanh(2); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.atanh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.acosh()")}}
- {{jsxref("Math.asinh()")}}
- {{jsxref("Math.cosh()")}}
- {{jsxref("Math.sinh()")}}
- {{jsxref("Math.tanh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/fround/index.md | ---
title: Math.fround()
slug: Web/JavaScript/Reference/Global_Objects/Math/fround
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.fround
---
{{JSRef}}
The **`Math.fround()`** static method returns the nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of a number.
{{EmbedInteractiveExample("pages/js/math-fround.html")}}
## Syntax
```js-nolint
Math.fround(doubleFloat)
```
### Parameters
- `doubleFloat`
- : A number.
### Return value
The nearest [32-bit single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) float representation of `x`.
## Description
JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a {{jsxref("Float32Array")}}. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.
To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, {{jsxref("Infinity")}} or `-Infinity` is returned.
Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.fround()
The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:
```js
Math.fround(1.5); // 1.5
Math.fround(1.5) === 1.5; // true
```
However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:
```js
Math.fround(1.337); // 1.3370000123977661
Math.fround(1.337) === 1.337; // false
```
<math><semantics><msup><mn>2</mn><mn>150</mn></msup><annotation encoding="TeX">2^150</annotation></semantics></math> is too big for a 32-bit float, so `Infinity` is returned:
```js
2 ** 150; // 1.42724769270596e+45
Math.fround(2 ** 150); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.fround` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.round()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/abs/index.md | ---
title: Math.abs()
slug: Web/JavaScript/Reference/Global_Objects/Math/abs
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.abs
---
{{JSRef}}
The **`Math.abs()`** static method returns the absolute value of a number.
{{EmbedInteractiveExample("pages/js/math-abs.html")}}
## Syntax
```js-nolint
Math.abs(x)
```
### Parameters
- `x`
- : A number.
### Return value
The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`.
## Description
Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.abs()
```js
Math.abs(-Infinity); // Infinity
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // Infinity
```
### Coercion of parameter
`Math.abs()` [coerces its parameter to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). Non-coercible values will become `NaN`, making `Math.abs()` also return `NaN`.
```js
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.ceil()")}}
- {{jsxref("Math.floor()")}}
- {{jsxref("Math.round()")}}
- {{jsxref("Math.sign()")}}
- {{jsxref("Math.trunc()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log1p/index.md | ---
title: Math.log1p()
slug: Web/JavaScript/Reference/Global_Objects/Math/log1p
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.log1p
---
{{JSRef}}
The **`Math.log1p()`** static method returns the natural logarithm (base [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E)) of `1 + x`, where `x` is the argument. That is:
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mo>−</mo><mn>1</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝚙</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="TeX">\forall x > -1,\;\mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-log1p.html")}}
## Syntax
```js-nolint
Math.log1p(x)
```
### Parameters
- `x`
- : A number greater than or equal to -1.
### Return value
The natural logarithm (base [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E)) of `x + 1`. If `x` is -1, returns [`-Infinity`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY). If `x < -1`, returns {{jsxref("NaN")}}.
## Description
For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.
When you calculate log(1 + _x_) where _x_ is a small positive number, you should get an answer very close to _x_, because <math display="inline"><semantics><mrow><munder><mo movablelimits="true" form="prefix">lim</mo><mrow ><mi>x</mi><mo stretchy="false">→</mo><mn>0</mn></mrow></munder><mfrac><mrow><mi>log</mi><mo></mo><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><mi>x</mi></mfrac><mo>=</mo><mn>1</mn></mrow><annotation encoding="TeX">\lim\_{x \to 0} \frac{\log(1+x)}{x} = 1</annotation></semantics></math>. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case).
If the value of `x` is less than -1, the return value is always {{jsxref("NaN")}}.
Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.log1p()
```js
Math.log1p(-2); // NaN
Math.log1p(-1); // -Infinity
Math.log1p(-0); // -0
Math.log1p(0); // 0
Math.log1p(1); // 0.6931471805599453
Math.log1p(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.log1p` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.expm1()")}}
- {{jsxref("Math.log10()")}}
- {{jsxref("Math.log2()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/clz32/index.md | ---
title: Math.clz32()
slug: Web/JavaScript/Reference/Global_Objects/Math/clz32
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.clz32
---
{{JSRef}}
The **`Math.clz32()`** static method returns the number of leading zero bits in the 32-bit binary representation of a number.
{{EmbedInteractiveExample("pages/js/math-clz32.html")}}
## Syntax
```js-nolint
Math.clz32(x)
```
### Parameters
- `x`
- : A number.
### Return value
The number of leading zero bits in the 32-bit binary representation of `x`.
## Description
`clz32` is short for **C**ount**L**eading**Z**eros**32**.
If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer.
If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 2<sup>31</sup>), `0` is returned.
This function is particularly useful for systems that compile to JS, like [Emscripten](https://emscripten.org).
## Examples
### Using Math.clz32()
```js
Math.clz32(1); // 31
Math.clz32(1000); // 22
Math.clz32(); // 32
const stuff = [
NaN,
Infinity,
-Infinity,
0,
-0,
false,
null,
undefined,
"foo",
{},
[],
];
stuff.every((n) => Math.clz32(n) === 32); // true
Math.clz32(true); // 31
Math.clz32(3.5); // 30
```
### Implementing Count Leading Ones and beyond
At present, there is no `Math.clon` for "Count Leading Ones" (named "clon", not "clo", because "clo" and "clz" are too similar especially for non-English-speaking people). However, a `clon` function can easily be created by inverting the bits of a number and passing the result to `Math.clz32`. Doing this will work because the inverse of 1 is 0 and vice versa. Thus, inverting the bits will inverse the measured quantity of 0's (from `Math.clz32`), thereby making `Math.clz32` count the number of ones instead of counting the number of zeros.
Consider the following 32-bit word:
```js
const a = 32776; // 00000000000000001000000000001000 (16 leading zeros)
Math.clz32(a); // 16
const b = ~32776; // 11111111111111110111111111110111 (32776 inverted, 0 leading zeros)
Math.clz32(b); // 0 (this is equal to how many leading one's there are in a)
```
Using this logic, a `clon` function can be created as follows:
```js
const clz = Math.clz32;
function clon(integer) {
return clz(~integer);
}
```
Further, this technique could be extended to create a jumpless "Count Trailing Zeros" function, as seen below. The `ctrz` function takes a bitwise AND of the integer with its two's complement. By how two's complement works, all trailing zeros will be converted to ones, and then when adding 1, it would be carried over until the first `0` (which was originally a `1`) is reached. All bits higher than this one stay the same and are inverses of the original integer's bits. Therefore, when doing bitwise AND with the original integer, all higher bits become `0`, which can be counted with `clz`. The number of trailing zeros, plus the first `1` bit, plus the leading bits that were counted by `clz`, total to 32.
```js
function ctrz(integer) {
integer >>>= 0; // coerce to Uint32
if (integer === 0) {
// skipping this step would make it return -1
return 32;
}
integer &= -integer; // equivalent to `int = int & (~int + 1)`
return 31 - clz(integer);
}
```
Then we can define a "Count Trailing Ones" function like so:
```js
function ctron(integer) {
return ctrz(~integer);
}
```
These helper functions can be made into an [asm.js](/en-US/docs/Games/Tools/asm.js) module for a potential performance improvement.
```js
const countTrailsMethods = (function (stdlib, foreign, heap) {
"use asm";
const clz = stdlib.Math.clz32;
// count trailing zeros
function ctrz(integer) {
integer = integer | 0; // coerce to an integer
if ((integer | 0) == 0) {
// skipping this step would make it return -1
return 32;
}
// Note: asm.js doesn't have compound assignment operators such as &=
integer = integer & -integer; // equivalent to `int = int & (~int + 1)`
return (31 - clz(integer)) | 0;
}
// count trailing ones
function ctron(integer) {
integer = integer | 0; // coerce to an integer
return ctrz(~integer) | 0;
}
// asm.js demands plain objects:
return { ctrz: ctrz, ctron: ctron };
})(window, null, null);
const { ctrz, ctron } = countTrailsMethods;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.clz32` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math")}}
- {{jsxref("Math.imul")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log/index.md | ---
title: Math.log()
slug: Web/JavaScript/Reference/Global_Objects/Math/log
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.log
---
{{JSRef}}
The **`Math.log()`** static method returns the natural logarithm (base [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E)) of a number. That is
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mn>0</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚕𝚘𝚐</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><msup><mi>e</mi><mi>y</mi></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x > 0,\;\mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique } y \text{ such that } e^y = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-log.html")}}
## Syntax
```js-nolint
Math.log(x)
```
### Parameters
- `x`
- : A number greater than or equal to 0.
### Return value
The natural logarithm (base [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E)) of `x`. If `x` is ±0, returns [`-Infinity`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY). If `x < 0`, returns {{jsxref("NaN")}}.
## Description
Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
If you need the natural log of 2 or 10, use the constants {{jsxref("Math.LN2")}} or {{jsxref("Math.LN10")}}. If you need a logarithm to base 2 or 10, use {{jsxref("Math.log2()")}} or {{jsxref("Math.log10()")}}. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster.
Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use {{jsxref("Math.log1p")}} instead.
## Examples
### Using Math.log()
```js
Math.log(-1); // NaN
Math.log(-0); // -Infinity
Math.log(0); // -Infinity
Math.log(1); // 0
Math.log(10); // 2.302585092994046
Math.log(Infinity); // Infinity
```
### Using Math.log() with a different base
The following function returns the logarithm of `y` with base `x` (i.e. <math><semantics><mrow><msub><mo>log</mo><mi>x</mi></msub><mi>y</mi></mrow><annotation encoding="TeX">\log_x y</annotation></semantics></math>):
```js
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
```
If you run `getBaseLog(10, 1000)`, it returns `2.9999999999999996` due to floating-point rounding, but still very close to the actual answer of 3.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log1p()")}}
- {{jsxref("Math.log10()")}}
- {{jsxref("Math.log2()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/ceil/index.md | ---
title: Math.ceil()
slug: Web/JavaScript/Reference/Global_Objects/Math/ceil
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.ceil
---
{{JSRef}}
The **`Math.ceil()`** static method always rounds up and returns the smallest integer greater than or equal to a given number.
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
## Syntax
```js-nolint
Math.ceil(x)
```
### Parameters
- `x`
- : A number.
### Return value
The smallest integer greater than or equal to `x`. It's the same value as [`-Math.floor(-x)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor).
## Description
Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.ceil()
```js
Math.ceil(-Infinity); // -Infinity
Math.ceil(-7.004); // -7
Math.ceil(-4); // -4
Math.ceil(-0.95); // -0
Math.ceil(-0); // -0
Math.ceil(0); // 0
Math.ceil(0.95); // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.floor()")}}
- {{jsxref("Math.round()")}}
- {{jsxref("Math.sign()")}}
- {{jsxref("Math.trunc()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/pi/index.md | ---
title: Math.PI
slug: Web/JavaScript/Reference/Global_Objects/Math/PI
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.PI
---
{{JSRef}}
The **`Math.PI`** static data property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.
{{EmbedInteractiveExample("pages/js/math-pi.html")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙿𝙸</mi><mo>=</mo><mi>π</mi><mo>≈</mo><mn>3.14159</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.PI}} = \pi \approx 3.14159</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.PI
The following function uses `Math.PI` to calculate the circumference of a circle with a passed radius.
```js
function calculateCircumference(radius) {
return Math.PI * (radius + radius);
}
calculateCircumference(1); // 6.283185307179586
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sqrt1_2/index.md | ---
title: Math.SQRT1_2
slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.SQRT1_2
---
{{JSRef}}
The **`Math.SQRT1_2`** static data property represents the square root of 1/2, which is approximately 0.707.
{{EmbedInteractiveExample("pages/js/math-sqrt1_2.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟷_𝟸</mi><mo>=</mo><msqrt><mfrac><mn>1</mn><mn>2</mn></mfrac></msqrt><mo>≈</mo><mn>0.707</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.SQRT1_2}} = \sqrt{\frac{1}{2}} \approx 0.707</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
`Math.SQRT1_2` is a constant and a more performant equivalent to [`Math.sqrt(0.5)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt).
Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.SQRT1_2
The following function returns 1 over the square root of 2:
```js
function getRoot1_2() {
return Math.SQRT1_2;
}
getRoot1_2(); // 0.7071067811865476
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.pow()")}}
- {{jsxref("Math.sqrt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sinh/index.md | ---
title: Math.sinh()
slug: Web/JavaScript/Reference/Global_Objects/Math/sinh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.sinh
---
{{JSRef}}
The **`Math.sinh()`** static method returns the hyperbolic sine of a number. That is,
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚜𝚒𝚗𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">sinh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>−</mo><msup><mi mathvariant="normal">e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow><mn>2</mn></mfrac></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.sinh}(x)} = \sinh(x) = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{2}</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-sinh.html")}}
## Syntax
```js-nolint
Math.sinh(x)
```
### Parameters
- `x`
- : A number.
### Return value
The hyperbolic sine of `x`.
## Description
Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.sinh()
```js
Math.sinh(-Infinity); // -Infinity
Math.sinh(-0); // -0
Math.sinh(0); // 0
Math.sinh(1); // 1.1752011936438014
Math.sinh(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.sinh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.acosh()")}}
- {{jsxref("Math.asinh()")}}
- {{jsxref("Math.atanh()")}}
- {{jsxref("Math.cosh()")}}
- {{jsxref("Math.tanh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/round/index.md | ---
title: Math.round()
slug: Web/JavaScript/Reference/Global_Objects/Math/round
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.round
---
{{JSRef}}
The **`Math.round()`** static method returns the value of a number rounded to the nearest integer.
{{EmbedInteractiveExample("pages/js/math-round.html")}}
## Syntax
```js-nolint
Math.round(x)
```
### Parameters
- `x`
- : A number.
### Return value
The value of `x` rounded to the nearest integer.
## Description
If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.
> **Note:** This differs from many languages' `round()` functions, which often round half-increments _away from zero_, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.
`Math.round(x)` is not exactly the same as [`Math.floor(x + 0.5)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor). When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent.
Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor).
## Examples
### Using round
```js
Math.round(-Infinity); // -Infinity
Math.round(-20.51); // -21
Math.round(-20.5); // -20
Math.round(-0.1); // -0
Math.round(0); // 0
Math.round(20.49); // 20
Math.round(20.5); // 21
Math.round(42); // 42
Math.round(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Number.prototype.toPrecision()")}}
- {{jsxref("Number.prototype.toFixed()")}}
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.ceil()")}}
- {{jsxref("Math.floor()")}}
- {{jsxref("Math.sign()")}}
- {{jsxref("Math.trunc()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/acos/index.md | ---
title: Math.acos()
slug: Web/JavaScript/Reference/Global_Objects/Math/acos
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.acos
---
{{JSRef}}
The **`Math.acos()`** static method returns the inverse cosine (in radians) of a number. That is,
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>∊</mo><mo stretchy="false">[</mo><mrow><mo>−</mo><mn>1</mn></mrow><mo>,</mo><mn>1</mn><mo stretchy="false">]</mo><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">arccos</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mo>∊</mo><mo stretchy="false">[</mo><mn>0</mn><mo>,</mo><mi>π</mi><mo stretchy="false">]</mo><mtext> such that </mtext><mo lspace="0em" rspace="0em">cos</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \in [{-1}, 1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{the unique } y \in [0, \pi] \text{ such that } \cos(y) = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-acos.html")}}
## Syntax
```js-nolint
Math.acos(x)
```
### Parameters
- `x`
- : A number between -1 and 1, inclusive, representing the angle's cosine value.
### Return value
The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns {{jsxref("NaN")}}.
## Description
Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.acos()
```js
Math.acos(-2); // NaN
Math.acos(-1); // 3.141592653589793 (π)
Math.acos(0); // 1.5707963267948966 (π/2)
Math.acos(0.5); // 1.0471975511965979 (π/3)
Math.acos(1); // 0
Math.acos(2); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.sin()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/ln2/index.md | ---
title: Math.LN2
slug: Web/JavaScript/Reference/Global_Objects/Math/LN2
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.LN2
---
{{JSRef}}
The **`Math.LN2`** static data property represents the natural logarithm of 2, approximately 0.693:
{{EmbedInteractiveExample("pages/js/math-ln2.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙻𝙽𝟸</mi><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo><mo>≈</mo><mn>0.693</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.LN2
The following function returns the natural log of 2:
```js
function getNatLog2() {
return Math.LN2;
}
getNatLog2(); // 0.6931471805599453
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log2()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log2/index.md | ---
title: Math.log2()
slug: Web/JavaScript/Reference/Global_Objects/Math/log2
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.log2
---
{{JSRef}}
The **`Math.log2()`** static method returns the base 2 logarithm of a number. That is
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mn>0</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟸</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>2</mn></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><msup><mn>2</mn><mi>y</mi></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x > 0,\;\mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique } y \text{ such that } 2^y = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-log2.html")}}
## Syntax
```js-nolint
Math.log2(x)
```
### Parameters
- `x`
- : A number greater than or equal to 0.
### Return value
The base 2 logarithm of `x`. If `x < 0`, returns {{jsxref("NaN")}}.
## Description
Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant {{jsxref("Math.LOG2E")}}, which is 1 / {{jsxref("Math.LN2")}}.
## Examples
### Using Math.log2()
```js
Math.log2(-2); // NaN
Math.log2(-0); // -Infinity
Math.log2(0); // -Infinity
Math.log2(1); // 0
Math.log2(2); // 1
Math.log2(3); // 1.584962500721156
Math.log2(1024); // 10
Math.log2(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.log2` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log10()")}}
- {{jsxref("Math.log1p()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/tan/index.md | ---
title: Math.tan()
slug: Web/JavaScript/Reference/Global_Objects/Math/tan
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.tan
---
{{JSRef}}
The **`Math.tan()`** static method returns the tangent of a number in radians.
{{EmbedInteractiveExample("pages/js/math-tan.html")}}
## Syntax
```js-nolint
Math.tan(x)
```
### Parameters
- `x`
- : A number representing an angle in radians.
### Return value
The tangent of `x`. If `x` is {{jsxref("Infinity")}}, `-Infinity`, or {{jsxref("NaN")}}, returns {{jsxref("NaN")}}.
> **Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`.
## Description
Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.tan()
```js
Math.tan(-Infinity); // NaN
Math.tan(-0); // -0
Math.tan(0); // 0
Math.tan(1); // 1.5574077246549023
Math.tan(Math.PI / 4); // 0.9999999999999999 (Floating point error)
Math.tan(Infinity); // NaN
```
### Math.tan() and π/2
It's not possible to calculate `tan(π/2)` exactly.
```js
Math.tan(Math.PI / 2); // 16331239353195370
Math.tan(Math.PI / 2 + Number.EPSILON); // -6218431163823738
```
### Using Math.tan() with a degree value
Because the `Math.tan()` function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.
```js
function getTanDeg(deg) {
const rad = (deg * Math.PI) / 180;
return Math.tan(rad);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.sin()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log2e/index.md | ---
title: Math.LOG2E
slug: Web/JavaScript/Reference/Global_Objects/Math/LOG2E
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.LOG2E
---
{{JSRef}}
The **`Math.LOG2E`** static data property represents the base 2 logarithm of [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E), approximately 1.442.
{{EmbedInteractiveExample("pages/js/math-log2e.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟸𝙴</mi><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>2</mn></msub><mo stretchy="false">(</mo><mi mathvariant="normal">e</mi><mo stretchy="false">)</mo><mo>≈</mo><mn>1.442</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LOG2E}} = \log_2(\mathrm{e}) \approx 1.442</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.LOG2E
The following function returns the base 2 logarithm of e:
```js
function getLog2e() {
return Math.LOG2E;
}
getLog2e(); // 1.4426950408889634
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log2()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log10/index.md | ---
title: Math.log10()
slug: Web/JavaScript/Reference/Global_Objects/Math/log10
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.log10
---
{{JSRef}}
The **`Math.log10()`** static method returns the base 10 logarithm of a number. That is
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mn>0</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝟶</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>10</mn></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><msup><mn>10</mn><mi>y</mi></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x > 0,\;\mathtt{\operatorname{Math.log10}(x)} = \log\_{10}(x) = \text{the unique } y \text{ such that } 10^y = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-log10.html")}}
## Syntax
```js-nolint
Math.log10(x)
```
### Parameters
- `x`
- : A number greater than or equal to 0.
### Return value
The base 10 logarithm of `x`. If `x < 0`, returns {{jsxref("NaN")}}.
## Description
Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant {{jsxref("Math.LOG10E")}}, which is 1 / {{jsxref("Math.LN10")}}.
## Examples
### Using Math.log10()
```js
Math.log10(-2); // NaN
Math.log10(-0); // -Infinity
Math.log10(0); // -Infinity
Math.log10(1); // 0
Math.log10(2); // 0.3010299956639812
Math.log10(100000); // 5
Math.log10(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.log10` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log1p()")}}
- {{jsxref("Math.log2()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sin/index.md | ---
title: Math.sin()
slug: Web/JavaScript/Reference/Global_Objects/Math/sin
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.sin
---
{{JSRef}}
The **`Math.sin()`** static method returns the sine of a number in radians.
{{EmbedInteractiveExample("pages/js/math-sin.html")}}
## Syntax
```js-nolint
Math.sin(x)
```
### Parameters
- `x`
- : A number representing an angle in radians.
### Return value
The sine of `x`, between -1 and 1, inclusive. If `x` is {{jsxref("Infinity")}}, `-Infinity`, or {{jsxref("NaN")}}, returns {{jsxref("NaN")}}.
## Description
Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.sin()
```js
Math.sin(-Infinity); // NaN
Math.sin(-0); // -0
Math.sin(0); // 0
Math.sin(1); // 0.8414709848078965
Math.sin(Math.PI / 2); // 1
Math.sin(Infinity); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/cbrt/index.md | ---
title: Math.cbrt()
slug: Web/JavaScript/Reference/Global_Objects/Math/cbrt
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.cbrt
---
{{JSRef}}
The **`Math.cbrt()`** static method returns the cube root of a number. That is
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚌𝚋𝚛𝚝</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mroot><mi>x</mi><mn>3</mn></mroot><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><msup><mi>y</mi><mn>3</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.cbrt}(x)} = \sqrt[3]{x} = \text{the unique } y \text{ such that } y^3 = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-cbrt.html")}}
## Syntax
```js-nolint
Math.cbrt(x)
```
### Parameters
- `x`
- : A number.
### Return value
The cube root of `x`.
## Description
Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.cbrt()
```js
Math.cbrt(-Infinity); // -Infinity
Math.cbrt(-1); // -1
Math.cbrt(-0); // -0
Math.cbrt(0); // 0
Math.cbrt(1); // 1
Math.cbrt(2); // 1.2599210498948732
Math.cbrt(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.cbrt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.pow()")}}
- {{jsxref("Math.sqrt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/trunc/index.md | ---
title: Math.trunc()
slug: Web/JavaScript/Reference/Global_Objects/Math/trunc
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.trunc
---
{{JSRef}}
The **`Math.trunc()`** static method returns the integer part of a number by removing any fractional digits.
{{EmbedInteractiveExample("pages/js/math-trunc.html")}}
## Syntax
```js-nolint
Math.trunc(x)
```
### Parameters
- `x`
- : A number.
### Return value
The integer part of `x`.
## Description
Unlike the other three `Math` methods: {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} and {{jsxref("Math.round()")}}, the way `Math.trunc()` works is very simple. It _truncates_ (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.
Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.trunc()
```js
Math.trunc(-Infinity); // -Infinity
Math.trunc("-1.123"); // -1
Math.trunc(-0.123); // -0
Math.trunc(-0); // -0
Math.trunc(0); // 0
Math.trunc(0.123); // 0
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(Infinity); // Infinity
```
### Using bitwise no-ops to truncate numbers
> **Warning:** This is not a polyfill for `Math.trunc()` because of non-negligible edge cases.
Bitwise operations convert their operands to 32-bit integers, which people have historically taken advantage of to truncate float-point numbers. Common techniques include:
```js
const original = 3.14;
const truncated1 = ~~original; // Double negation
const truncated2 = original & -1; // Bitwise AND with -1
const truncated3 = original | 0; // Bitwise OR with 0
const truncated4 = original ^ 0; // Bitwise XOR with 0
const truncated5 = original >> 0; // Bitwise shifting by 0
```
Beware that this is essentially `toInt32`, which is not the same as `Math.trunc`. When the value does not satisfy -2<sup>31</sup> - 1 < `value` < 2<sup>31</sup> (-2147483649 < `value` < 2147483648), the conversion would overflow.
```js
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0
```
Only use `~~` as a substitution for `Math.trunc()` when you are confident that the range of input falls within the range of 32-bit integers.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.trunc` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.ceil()")}}
- {{jsxref("Math.floor()")}}
- {{jsxref("Math.round()")}}
- {{jsxref("Math.sign()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/atan/index.md | ---
title: Math.atan()
slug: Web/JavaScript/Reference/Global_Objects/Math/atan
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.atan
---
{{JSRef}}
The **`Math.atan()`** static method returns the inverse tangent (in radians) of a number, that is
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">arctan</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mo>∊</mo><mrow><mo>[</mo><mrow><mo>−</mo><mfrac><mi>π</mi><mn>2</mn></mfrac><mo>,</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><mo>]</mo></mrow><mtext> such that </mtext><mo lspace="0em" rspace="0em">tan</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \tan(y) = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-atan.html")}}
## Syntax
```js-nolint
Math.atan(x)
```
### Parameters
- `x`
- : A number.
### Return value
The inverse tangent (angle in radians between <math><semantics><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><annotation encoding="TeX">-\frac{\pi}{2}</annotation></semantics></math> and <math><semantics><mfrac><mi>π</mi><mn>2</mn></mfrac><annotation encoding="TeX">\frac{\pi}{2}</annotation></semantics></math>, inclusive) of `x`. If `x` is {{jsxref("Infinity")}}, it returns <math><semantics><mfrac><mi>π</mi><mn>2</mn></mfrac><annotation encoding="TeX">\frac{\pi}{2}</annotation></semantics></math>. If `x` is `-Infinity`, it returns <math><semantics><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><annotation encoding="TeX">-\frac{\pi}{2}</annotation></semantics></math>.
## Description
Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.atan()
```js
Math.atan(-Infinity); // -1.5707963267948966 (-π/2)
Math.atan(-0); // -0
Math.atan(0); // 0
Math.atan(1); // 0.7853981633974483 (π/4)
Math.atan(Infinity); // 1.5707963267948966 (π/2)
// The angle that the line (0,0) -- (x,y) forms with the x-axis in a Cartesian coordinate system
const theta = (x, y) => Math.atan(y / x);
```
Note that you may want to avoid the `theta` function and use {{jsxref("Math.atan2()")}} instead, which has a wider range (between -π and π) and avoids outputting `NaN` for cases such as when `x` is `0`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.sin()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/atan2/index.md | ---
title: Math.atan2()
slug: Web/JavaScript/Reference/Global_Objects/Math/atan2
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.atan2
---
{{JSRef}}
The **`Math.atan2()`** static method returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`.
{{EmbedInteractiveExample("pages/js/math-atan2.html")}}
## Syntax
```js-nolint
Math.atan2(y, x)
```
### Parameters
- `y`
- : The y coordinate of the point.
- `x`
- : The x coordinate of the point.
### Return value
The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y).
## Description
The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

`Math.atan2()` is passed separate `x` and `y` arguments, while [`Math.atan()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan) is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases:
| `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` |
| -------------------- | ----------- | ------------------ | ------------------ |
| `Infinity` | `Infinity` | π / 4 | `NaN` |
| `Infinity` | `-Infinity` | -π / 4 | `NaN` |
| `-Infinity` | `Infinity` | 3π / 4 | `NaN` |
| `-Infinity` | `-Infinity` | -3π / 4 | `NaN` |
| 0 | 0 | 0 | `NaN` |
| 0 | -0 | -0 | `NaN` |
| < 0 (including `-0`) | 0 | π | 0 |
| < 0 (including `-0`) | -0 | -π | 0 |
| `-Infinity` | > 0 | π | -0 |
| -0 | > 0 | π / 2 | -π / 2 |
| `-Infinity` | < 0 | -π | 0 |
| -0 | < 0 | -π / 2 | π / 2 |
In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than <math><semantics><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><annotation encoding="TeX">-\frac{\pi}{2}</annotation></semantics></math> or greater than <math><semantics><mfrac><mi>π</mi><mn>2</mn></mfrac><annotation encoding="TeX">\frac{\pi}{2}</annotation></semantics></math>.
Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.atan2()
```js
Math.atan2(90, 15); // 1.4056476493802699
Math.atan2(15, 90); // 0.16514867741462683
```
### Difference between Math.atan2(y, x) and Math.atan(y / x)
The following script prints all inputs that produce a difference between `Math.atan2(y, x)` and `Math.atan(y / x)`.
```js
const formattedNumbers = new Map([
[-Math.PI, "-π"],
[(-3 * Math.PI) / 4, "-3π/4"],
[-Math.PI / 2, "-π/2"],
[-Math.PI / 4, "-π/4"],
[Math.PI / 4, "π/4"],
[Math.PI / 2, "π/2"],
[(3 * Math.PI) / 4, "3π/4"],
[Math.PI, "π"],
[-Infinity, "-∞"],
[Infinity, "∞"],
]);
function format(template, ...args) {
return String.raw(
{ raw: template },
...args.map((num) =>
(Object.is(num, -0)
? "-0"
: formattedNumbers.get(num) ?? String(num)
).padEnd(5),
),
);
}
console.log(`| x | y | atan2 | atan |
|-------|-------|-------|-------|`);
for (const x of [-Infinity, -1, -0, 0, 1, Infinity]) {
for (const y of [-Infinity, -1, -0, 0, 1, Infinity]) {
const atan2 = Math.atan2(y, x);
const atan = Math.atan(y / x);
if (!Object.is(atan2, atan)) {
console.log(format`| ${x} | ${y} | ${atan2} | ${atan} |`);
}
}
}
```
The output is:
```plain
| x | y | atan2 | atan |
|-------|-------|-------|-------|
| -∞ | -∞ | -3π/4 | NaN |
| -∞ | -1 | -π | 0 |
| -∞ | -0 | -π | 0 |
| -∞ | 0 | π | -0 |
| -∞ | 1 | π | -0 |
| -∞ | ∞ | 3π/4 | NaN |
| -1 | -∞ | -π/2 | π/2 |
| -1 | -1 | -3π/4 | π/4 |
| -1 | -0 | -π | 0 |
| -1 | 0 | π | -0 |
| -1 | 1 | 3π/4 | -π/4 |
| -1 | ∞ | π/2 | -π/2 |
| -0 | -∞ | -π/2 | π/2 |
| -0 | -1 | -π/2 | π/2 |
| -0 | -0 | -π | NaN |
| -0 | 0 | π | NaN |
| -0 | 1 | π/2 | -π/2 |
| -0 | ∞ | π/2 | -π/2 |
| 0 | -0 | -0 | NaN |
| 0 | 0 | 0 | NaN |
| ∞ | -∞ | -π/4 | NaN |
| ∞ | ∞ | π/4 | NaN |
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.asin()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.sin()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sign/index.md | ---
title: Math.sign()
slug: Web/JavaScript/Reference/Global_Objects/Math/sign
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.sign
---
{{JSRef}}
The **`Math.sign()`** static method returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is.
{{EmbedInteractiveExample("pages/js/math-sign.html")}}
## Syntax
```js-nolint
Math.sign(x)
```
### Parameters
- `x`
- : A number.
### Return value
A number representing the sign of `x`:
- If `x` is positive, returns `1`.
- If `x` is negative, returns `-1`.
- If `x` is positive zero, returns `0`.
- If `x` is negative zero, returns `-0`.
- Otherwise, returns {{jsxref("NaN")}}.
## Description
Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.sign()
```js
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign("-3"); // -1
Math.sign(0); // 0
Math.sign(-0); // -0
Math.sign(NaN); // NaN
Math.sign("foo"); // NaN
Math.sign(); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.sign` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.ceil()")}}
- {{jsxref("Math.floor()")}}
- {{jsxref("Math.round()")}}
- {{jsxref("Math.trunc()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/min/index.md | ---
title: Math.min()
slug: Web/JavaScript/Reference/Global_Objects/Math/min
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.min
---
{{JSRef}}
The **`Math.min()`** static method returns the smallest of the numbers given as input parameters, or {{jsxref("Infinity")}} if there are no parameters.
{{EmbedInteractiveExample("pages/js/math-min.html")}}
## Syntax
```js-nolint
Math.min()
Math.min(value1)
Math.min(value1, value2)
Math.min(value1, value2, /* …, */ valueN)
```
### Parameters
- `value1`, …, `valueN`
- : Zero or more numbers among which the lowest value will be selected and returned.
### Return value
The smallest of the given numbers. Returns {{jsxref("NaN")}} if any of the parameters is or is converted into `NaN`. Returns {{jsxref("Infinity")}} if no parameters are provided.
## Description
Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
[`Math.min.length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
## Examples
### Using Math.min()
This finds the min of `x` and `y` and assigns it to `z`:
```js
const x = 10;
const y = -20;
const z = Math.min(x, y); // -20
```
### Clipping a value with Math.min()
`Math.min()` is often used to clip a value so that it is always less than or
equal to a boundary. For instance, this
```js
let x = f(foo);
if (x > boundary) {
x = boundary;
}
```
may be written as this
```js
const x = Math.min(f(foo), boundary);
```
{{jsxref("Math.max()")}} can be used in a similar way to clip a value at the other end.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.max()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/log10e/index.md | ---
title: Math.LOG10E
slug: Web/JavaScript/Reference/Global_Objects/Math/LOG10E
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.LOG10E
---
{{JSRef}}
The **`Math.LOG10E`** static data property represents the base 10 logarithm of [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E), approximately 0.434.
{{EmbedInteractiveExample("pages/js/math-log10e.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟷𝟶𝙴</mi><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>10</mn></msub><mo stretchy="false">(</mo><mi mathvariant="normal">e</mi><mo stretchy="false">)</mo><mo>≈</mo><mn>0.434</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LOG10E}} = \log\_{10}(\mathrm{e}) \approx 0.434</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.LOG10E
The following function returns the base 10 logarithm of e:
```js
function getLog10e() {
return Math.LOG10E;
}
getLog10e(); // 0.4342944819032518
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log10()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/asinh/index.md | ---
title: Math.asinh()
slug: Web/JavaScript/Reference/Global_Objects/Math/asinh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.asinh
---
{{JSRef}}
The **`Math.asinh()`** static method returns the inverse hyperbolic sine of a number. That is,
<math display="block"><semantics><mtable columnalign="right left right left right left right left right left" columnspacing="0em" displaystyle="true"><mtr><mtd><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow></mtd><mtd><mo>=</mo><mo lspace="0em" rspace="0.16666666666666666em">arsinh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mtext> such that </mtext><mo lspace="0em" rspace="0em">sinh</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mtd></mtr><mtr><mtd></mtd><mtd><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mrow><mo>(</mo><mrow><mi>x</mi><mo>+</mo><msqrt><mrow><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>1</mn></mrow></msqrt></mrow><mo>)</mo></mrow></mtd></mtr></mtable><annotation encoding="TeX">\begin{aligned}\mathtt{\operatorname{Math.asinh}(x)} &= \operatorname{arsinh}(x) = \text{the unique } y \text{ such that } \sinh(y) = x \\&= \ln\left(x + \sqrt{x^2 + 1}\right)\end{aligned}
</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-asinh.html")}}
## Syntax
```js-nolint
Math.asinh(x)
```
### Parameters
- `x`
- : A number.
### Return value
The inverse hyperbolic sine of `x`.
## Description
Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.asinh()
```js
Math.asinh(-Infinity); // -Infinity
Math.asinh(-1); // -0.881373587019543
Math.asinh(-0); // -0
Math.asinh(0); // 0
Math.asinh(1); // 0.881373587019543
Math.asinh(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.asinh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.acosh()")}}
- {{jsxref("Math.atanh()")}}
- {{jsxref("Math.cosh()")}}
- {{jsxref("Math.sinh()")}}
- {{jsxref("Math.tanh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/expm1/index.md | ---
title: Math.expm1()
slug: Web/JavaScript/Reference/Global_Objects/Math/expm1
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.expm1
---
{{JSRef}}
The **`Math.expm1()`** static method returns [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E) raised to the power of a number, subtracted by 1. That is
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚎𝚡𝚙𝚖𝟷</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>−</mo><mn>1</mn></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.expm1}(x)} = \mathrm{e}^x - 1</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-expm1.html")}}
## Syntax
```js-nolint
Math.expm1(x)
```
### Parameters
- `x`
- : A number.
### Return value
A number representing e<sup>x</sup> - 1, where e is [the base of the natural logarithm](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E).
## Description
For very small values of _x_, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 \= 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.
When you calculate <math display="inline"><semantics><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><annotation encoding="TeX">\mathrm{e}^x</annotation></semantics></math> where x is a number very close to 0, you should get an answer very close to 1 + x, because <math display="inline"><semantics><mrow><munder><mo lspace="0em" rspace="0em">lim</mo><mrow><mi>x</mi><mo stretchy="false">→</mo><mn>0</mn></mrow></munder><mfrac><mrow><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>−</mo><mn>1</mn></mrow><mi>x</mi></mfrac><mo>=</mo><mn>1</mn></mrow><annotation encoding="TeX">\lim\_{x \to 0} \frac{\mathrm{e}^x - 1}{x} = 1</annotation></semantics></math>. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision.
Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.expm1()
```js
Math.expm1(-Infinity); // -1
Math.expm1(-1); // -0.6321205588285577
Math.expm1(-0); // -0
Math.expm1(0); // 0
Math.expm1(1); // 1.718281828459045
Math.expm1(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.expm1` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.E")}}
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log10()")}}
- {{jsxref("Math.log1p()")}}
- {{jsxref("Math.log2()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/exp/index.md | ---
title: Math.exp()
slug: Web/JavaScript/Reference/Global_Objects/Math/exp
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.exp
---
{{JSRef}}
The **`Math.exp()`** static method returns [e](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E) raised to the power of a number. That is
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚎𝚡𝚙</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.exp}(x)} = \mathrm{e}^x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-exp.html")}}
## Syntax
```js-nolint
Math.exp(x)
```
### Parameters
- `x`
- : A number.
### Return value
A nonnegative number representing e<sup>x</sup>, where e is [the base of the natural logarithm](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E).
## Description
Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use {{jsxref("Math.expm1")}} instead, and obtain a much higher-precision fractional part of the answer.
## Examples
### Using Math.exp()
```js
Math.exp(-Infinity); // 0
Math.exp(-1); // 0.36787944117144233
Math.exp(0); // 1
Math.exp(1); // 2.718281828459045
Math.exp(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.E")}}
- {{jsxref("Math.expm1()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log10()")}}
- {{jsxref("Math.log1p()")}}
- {{jsxref("Math.log2()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/hypot/index.md | ---
title: Math.hypot()
slug: Web/JavaScript/Reference/Global_Objects/Math/hypot
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.hypot
---
{{JSRef}}
The **`Math.hypot()`** static method returns the square root of the sum of squares of its arguments. That is,
<math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚑𝚢𝚙𝚘𝚝</mo><mo stretchy="false">(</mo><msub><mi>v</mi><mn>1</mn></msub><mo>,</mo><msub><mi>v</mi><mn>2</mn></msub><mo>,</mo><mo>…</mo><mo>,</mo><msub><mi>v</mi><mi>n</mi></msub><mo stretchy="false">)</mo></mstyle><mo>=</mo><msqrt><mrow><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><msubsup><mi>v</mi><mi>i</mi><mn>2</mn></msubsup></mrow></msqrt><mo>=</mo><msqrt><mrow><msubsup><mi>v</mi><mn>1</mn><mn>2</mn></msubsup><mo>+</mo><msubsup><mi>v</mi><mn>2</mn><mn>2</mn></msubsup><mo>+</mo><mo>…</mo><mo>+</mo><msubsup><mi>v</mi><mi>n</mi><mn>2</mn></msubsup></mrow></msqrt></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum\_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-hypot.html")}}
## Syntax
```js-nolint
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ valueN)
```
### Parameters
- `value1`, …, `valueN`
- : Numbers.
### Return value
The square root of the sum of squares of the given arguments. Returns {{jsxref("Infinity")}} if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to {{jsxref("NaN")}}, returns {{jsxref("NaN")}}. Returns `0` if no arguments are given or all arguments are ±0.
## Description
Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`.
This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* …, */, vN)`.
`Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is [`Number.MAX_VALUE`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE), which is around 10<sup>308</sup>. If your numbers are larger than about 10<sup>154</sup>, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`.
With one argument, `Math.hypot()` is equivalent to [`Math.abs()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs). [`Math.hypot.length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.hypot()
```js
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(NaN, Infinity); // Infinity
Math.hypot(3, 4, "foo"); // NaN, since +'foo' => NaN
Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5
Math.hypot(-3); // 3, the same as Math.abs(-3)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.hypot` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.abs()")}}
- {{jsxref("Math.pow()")}}
- {{jsxref("Math.sqrt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/asin/index.md | ---
title: Math.asin()
slug: Web/JavaScript/Reference/Global_Objects/Math/asin
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.asin
---
{{JSRef}}
The **`Math.asin()`** static method returns the inverse sine (in radians) of a number. That is,
<math display="block" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>∊</mo><mo stretchy="false">[</mo><mrow><mo>−</mo><mn>1</mn></mrow><mo>,</mo><mn>1</mn><mo stretchy="false">]</mo><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">arcsin</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mo>∊</mo><mrow><mo>[</mo><mrow><mo>−</mo><mfrac><mi>π</mi><mn>2</mn></mfrac><mo>,</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><mo>]</mo></mrow><mtext> such that </mtext><mo lspace="0em" rspace="0em">sin</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \in [{-1}, 1],\;\mathtt{\operatorname{Math.asin}(x)} = \arcsin(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \sin(y) = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-asin.html")}}
## Syntax
```js-nolint
Math.asin(x)
```
### Parameters
- `x`
- : A number between -1 and 1, inclusive, representing the angle's sine value.
### Return value
The inverse sine (angle in radians between <math><semantics><mrow><mo>-</mo><mfrac><mi>π</mi><mn>2</mn></mfrac></mrow><annotation encoding="TeX">-\frac{\pi}{2}</annotation></semantics></math> and <math><semantics><mfrac><mi>π</mi><mn>2</mn></mfrac><annotation encoding="TeX">\frac{\pi}{2}</annotation></semantics></math>, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns {{jsxref("NaN")}}.
## Description
Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.asin()
```js
Math.asin(-2); // NaN
Math.asin(-1); // -1.5707963267948966 (-π/2)
Math.asin(-0); // -0
Math.asin(0); // 0
Math.asin(0.5); // 0.5235987755982989 (π/6)
Math.asin(1); // 1.5707963267948966 (π/2)
Math.asin(2); // NaN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.acos()")}}
- {{jsxref("Math.atan()")}}
- {{jsxref("Math.atan2()")}}
- {{jsxref("Math.cos()")}}
- {{jsxref("Math.sin()")}}
- {{jsxref("Math.tan()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/e/index.md | ---
title: Math.E
slug: Web/JavaScript/Reference/Global_Objects/Math/E
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.E
---
{{JSRef}}
The **`Math.E`** static data property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718.
{{EmbedInteractiveExample("pages/js/math-e.html")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝙴</mi><mo>=</mo><mi>e</mi><mo>≈</mo><mn>2.718</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.E}} = e \approx 2.718</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.E
The following function returns e:
```js
function getNapier() {
return Math.E;
}
getNapier(); // 2.718281828459045
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.log1p()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sqrt2/index.md | ---
title: Math.SQRT2
slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT2
page-type: javascript-static-data-property
browser-compat: javascript.builtins.Math.SQRT2
---
{{JSRef}}
The **`Math.SQRT2`** static data property represents the square root of 2, approximately 1.414.
{{EmbedInteractiveExample("pages/js/math-sqrt2.html", "shorter")}}
## Value
<math display="block"><semantics><mrow><mi>𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟸</mi><mo>=</mo><msqrt><mn>2</mn></msqrt><mo>≈</mo><mn>1.414</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414</annotation></semantics></math>
{{js_property_attributes(0, 0, 0)}}
## Description
`Math.SQRT2` is a constant and a more performant equivalent to [`Math.sqrt(2)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt).
Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.SQRT2
The following function returns the square root of 2:
```js
function getRoot2() {
return Math.SQRT2;
}
getRoot2(); // 1.4142135623730951
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.pow()")}}
- {{jsxref("Math.sqrt()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/acosh/index.md | ---
title: Math.acosh()
slug: Web/JavaScript/Reference/Global_Objects/Math/acosh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.acosh
---
{{JSRef}}
The **`Math.acosh()`** static method returns the inverse hyperbolic cosine of a number. That is,
<math display="block"><semantics><mtable columnalign="right left right left right left right left right left" columnspacing="0em" displaystyle="true"><mtr><mtd><mo>∀</mo><mi>x</mi><mo>≥</mo><mn>1</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow></mtd><mtd><mo>=</mo><mo lspace="0em" rspace="0.16666666666666666em">arcosh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mo>≥</mo><mn>0</mn><mtext> such that </mtext><mo lspace="0em" rspace="0em">cosh</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mtd></mtr><mtr><mtd></mtd><mtd><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mrow><mo>(</mo><mrow><mi>x</mi><mo>+</mo><msqrt><mrow><msup><mi>x</mi><mn>2</mn></msup><mo>−</mo><mn>1</mn></mrow></msqrt></mrow><mo>)</mo></mrow></mtd></mtr></mtable><annotation encoding="TeX">\begin{aligned}\forall x \geq 1,\;\mathtt{\operatorname{Math.acosh}(x)} &= \operatorname{arcosh}(x) = \text{the unique } y \geq 0 \text{ such that } \cosh(y) = x\\&= \ln\left(x + \sqrt{x^2 - 1}\right)\end{aligned}</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-acosh.html")}}
## Syntax
```js-nolint
Math.acosh(x)
```
### Parameters
- `x`
- : A number greater than or equal to 1.
### Return value
The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns {{jsxref("NaN")}}.
## Description
Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor).
## Examples
### Using Math.acosh()
```js
Math.acosh(0); // NaN
Math.acosh(1); // 0
Math.acosh(2); // 1.3169578969248166
Math.acosh(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.acosh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.asinh()")}}
- {{jsxref("Math.atanh()")}}
- {{jsxref("Math.cosh()")}}
- {{jsxref("Math.sinh()")}}
- {{jsxref("Math.tanh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/max/index.md | ---
title: Math.max()
slug: Web/JavaScript/Reference/Global_Objects/Math/max
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.max
---
{{JSRef}}
The **`Math.max()`** static method returns the largest of the numbers given as input parameters, or -{{jsxref("Infinity")}} if there are no parameters.
{{EmbedInteractiveExample("pages/js/math-max.html")}}
## Syntax
```js-nolint
Math.max()
Math.max(value1)
Math.max(value1, value2)
Math.max(value1, value2, /* …, */ valueN)
```
### Parameters
- `value1`, …, `valueN`
- : Zero or more numbers among which the largest value will be selected and returned.
### Return value
The largest of the given numbers. Returns {{jsxref("NaN")}} if any of the parameters is or is converted into `NaN`. Returns -{{jsxref("Infinity")}} if no parameters are provided.
## Description
Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
[`Math.max.length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) is 2, which weakly signals that it's designed to handle at least two parameters.
## Examples
### Using Math.max()
```js
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
```
### Getting the maximum element of an array
{{jsxref("Array.prototype.reduce()")}} can be used to find the maximum
element in a numeric array, by comparing each value:
```js
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
```
The following function uses {{jsxref("Function.prototype.apply()")}} to get the maximum of an array. `getMaxOfArray([1, 2, 3])` is equivalent to `Math.max(1, 2, 3)`, but you can use `getMaxOfArray()` on programmatically constructed arrays. This should only be used for arrays with relatively few elements.
```js
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
```
The [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) is a shorter way of writing the `apply` solution to get the maximum of an array:
```js
const arr = [1, 2, 3];
const max = Math.max(...arr);
```
However, both spread (`...`) and `apply` will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See [Using apply and built-in functions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#using_apply_and_built-in_functions) for more details. The `reduce` solution does not have this problem.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.min()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/tanh/index.md | ---
title: Math.tanh()
slug: Web/JavaScript/Reference/Global_Objects/Math/tanh
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.tanh
---
{{JSRef}}
The **`Math.tanh()`** static method returns the hyperbolic tangent of a number. That is,
<math display="block"><semantics><mrow><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚝𝚊𝚗𝚑</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><mo lspace="0em" rspace="0em">tanh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mo lspace="0em" rspace="0em">sinh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><mrow><mo lspace="0em" rspace="0em">cosh</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mfrac><mo>=</mo><mfrac><mrow><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>−</mo><msup><mi mathvariant="normal">e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow><mrow><msup><mi mathvariant="normal">e</mi><mi>x</mi></msup><mo>+</mo><msup><mi mathvariant="normal">e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow></mfrac><mo>=</mo><mfrac><mrow><msup><mi mathvariant="normal">e</mi><mrow><mn>2</mn><mi>x</mi></mrow></msup><mo>−</mo><mn>1</mn></mrow><mrow><msup><mi mathvariant="normal">e</mi><mrow><mn>2</mn><mi>x</mi></mrow></msup><mo>+</mo><mn>1</mn></mrow></mfrac></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.tanh}(x)} = \tanh(x) = \frac{\sinh(x)}{\cosh(x)} = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{\mathrm{e}^x + \mathrm{e}^{-x}} = \frac{\mathrm{e}^{2x} - 1}{\mathrm{e}^{2x}+1}</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-tanh.html")}}
## Syntax
```js-nolint
Math.tanh(x)
```
### Parameters
- `x`
- : A number.
### Return value
The hyperbolic tangent of `x`.
## Description
Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.tanh()
```js
Math.tanh(-Infinity); // -1
Math.tanh(-0); // -0
Math.tanh(0); // 0
Math.tanh(1); // 0.7615941559557649
Math.tanh(Infinity); // 1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.tanh` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- {{jsxref("Math.acosh()")}}
- {{jsxref("Math.asinh()")}}
- {{jsxref("Math.atanh()")}}
- {{jsxref("Math.cosh()")}}
- {{jsxref("Math.sinh()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/math | data/mdn-content/files/en-us/web/javascript/reference/global_objects/math/sqrt/index.md | ---
title: Math.sqrt()
slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.sqrt
---
{{JSRef}}
The **`Math.sqrt()`** static method returns the square root of a number. That is
<math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>≥</mo><mn>0</mn><mo>,</mo><mspace width="0.2777777777777778em"></mspace><mrow><mo lspace="0em" rspace="0.16666666666666666em">𝙼𝚊𝚝𝚑.𝚜𝚚𝚛𝚝</mo><mo stretchy="false">(</mo><mi>𝚡</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><msqrt><mi>x</mi></msqrt><mo>=</mo><mtext>the unique </mtext><mi>y</mi><mo>≥</mo><mn>0</mn><mtext> such that </mtext><msup><mi>y</mi><mn>2</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \geq 0,\;\mathtt{\operatorname{Math.sqrt}(x)} = \sqrt{x} = \text{the unique } y \geq 0 \text{ such that } y^2 = x</annotation></semantics></math>
{{EmbedInteractiveExample("pages/js/math-sqrt.html")}}
## Syntax
```js-nolint
Math.sqrt(x)
```
### Parameters
- `x`
- : A number greater than or equal to 0.
### Return value
The square root of `x`, a nonnegative number. If `x < 0`, returns {{jsxref("NaN")}}.
## Description
Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).
## Examples
### Using Math.sqrt()
```js
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Math.sqrt(0); // 0
Math.sqrt(1); // 1
Math.sqrt(2); // 1.414213562373095
Math.sqrt(9); // 3
Math.sqrt(Infinity); // Infinity
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Math.cbrt()")}}
- {{jsxref("Math.exp()")}}
- {{jsxref("Math.log()")}}
- {{jsxref("Math.pow()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/float64array/index.md | ---
title: Float64Array
slug: Web/JavaScript/Reference/Global_Objects/Float64Array
page-type: javascript-class
browser-compat: javascript.builtins.Float64Array
---
{{JSRef}}
The **`Float64Array`** typed array represents an array of 64-bit floating point numbers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
`Float64Array` is a subclass of the hidden {{jsxref("TypedArray")}} class.
## Constructor
- {{jsxref("Float64Array/Float64Array", "Float64Array()")}}
- : Creates a new `Float64Array` object.
## Static properties
_Also inherits static properties from its parent {{jsxref("TypedArray")}}_.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Float64Array.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `8` in the case of `Float64Array`.
## Static methods
_Inherits static methods from its parent {{jsxref("TypedArray")}}_.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("TypedArray")}}_.
These properties are defined on `Float64Array.prototype` and shared by all `Float64Array` instances.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Float64Array.prototype.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `8` in the case of a `Float64Array`.
- {{jsxref("Object/constructor", "Float64Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `Float64Array` instances, the initial value is the {{jsxref("Float64Array/Float64Array", "Float64Array")}} constructor.
## Instance methods
_Inherits instance methods from its parent {{jsxref("TypedArray")}}_.
## Examples
### Different ways to create a Float64Array
```js
// From a length
const float64 = new Float64Array(2);
float64[0] = 42;
console.log(float64[0]); // 42
console.log(float64.length); // 2
console.log(float64.BYTES_PER_ELEMENT); // 8
// From an array
const x = new Float64Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Float64Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new Float64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const float64FromIterable = new Float64Array(iterable);
console.log(float64FromIterable);
// Float64Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Float64Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/float64array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/float64array/float64array/index.md | ---
title: Float64Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array
page-type: javascript-constructor
browser-compat: javascript.builtins.Float64Array.Float64Array
---
{{JSRef}}
The **`Float64Array()`** constructor creates {{jsxref("Float64Array")}} objects. The contents are initialized to `0`.
## Syntax
```js-nolint
new Float64Array()
new Float64Array(length)
new Float64Array(typedArray)
new Float64Array(object)
new Float64Array(buffer)
new Float64Array(buffer, byteOffset)
new Float64Array(buffer, byteOffset, length)
```
> **Note:** `Float64Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create a Float64Array
```js
// From a length
const float64 = new Float64Array(2);
float64[0] = 42;
console.log(float64[0]); // 42
console.log(float64.length); // 2
console.log(float64.BYTES_PER_ELEMENT); // 8
// From an array
const x = new Float64Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Float64Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new Float64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const float64FromIterable = new Float64Array(iterable);
console.log(float64FromIterable);
// Float64Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Float64Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web | data/mdn-content/files/en-us/web/guide/index.md | ---
title: Developer guides
slug: Web/Guide
page-type: landing-page
---
<section id="Quick_links">
{{ListSubpagesForSidebar("/en-US/docs/Web/Guide")}}
</section>
There are a number of guides within MDN docs. These articles aim to add additional usage examples, or teach you how to use an API or feature. This page links to some of the most popular material.
## HTML
- [Structuring the web with HTML](/en-US/docs/Learn/HTML)
- : The HTML learning area offers tutorials to help you learn HTML from the ground up.
- [HTML basics](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics)
- : This article will give you a basic understanding of HTML. After following this guide, you can further explore the material in the HTML Learning Area.
## CSS
- [Learn to style HTML using CSS](/en-US/docs/Learn/CSS)
- : Our complete CSS tutorial, taking you from first steps through styling text, creating layouts, and more.
- [CSS Layout Guides](/en-US/docs/Web/Guide/CSS/CSS_Layout)
- : There are a large number of guides to CSS Layout across MDN, this page collects them all together.
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- : CSS animations make it possible to animate transitions from one CSS style configuration to another. This guide will help you get started with the animation properties.
## JavaScript
- [JavaScript learning area](/en-US/docs/Learn/JavaScript)
- : Whether you are a complete beginner, or hoping to refresh your skills, this is the place to start.
## Media
- [Audio and video delivery](/en-US/docs/Web/Media/Audio_and_video_delivery)
- : We can deliver audio and video on the web in several ways, ranging from 'static' media files to adaptive live streams. This article is intended as a starting point for exploring the various delivery mechanisms of web-based media and compatibility with popular browsers.
- [Audio and video manipulation](/en-US/docs/Web/Media/Audio_and_video_manipulation)
- : The beauty of the web is that you can combine technologies to create new forms. Having native audio and video in the browser means we can use these data streams with technologies such as {{htmlelement("canvas")}}, [WebGL](/en-US/docs/Web/API/WebGL_API) or [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. This article provides a reference to explain what you need to do.
## APIs
- [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)
- : The [`FormData`](/en-US/docs/Web/API/FormData) object lets you compile a set of key/value pairs to send using {{domxref("fetch()")}}. It's primarily intended for sending form data, but can be used independently of forms to transmit keyed data. The transmission is in the same format that the form's `submit()` method would use to send the data if the form's encoding type were set to "multipart/form-data".
- [Progressive web apps](/en-US/docs/Web/Progressive_web_apps#core_pwa_guides)
- : Progressive web apps (PWAs) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps. This set of guides tells you all you need to know about PWAs.
- [Parsing and serializing XML](/en-US/docs/Web/XML/Parsing_and_serializing_XML)
- : The web platform provides different methods of parsing and serializing XML, each with its pros and cons.
## Performance
- [Optimization and performance](/en-US/docs/Web/Performance)
- : When building modern web apps and sites, it's important to make your content work quickly and efficiently. This lets it perform effectively for both powerful desktop systems and weaker handheld devices.
## Mobile web development
- [Mobile web development](/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design)
- : This article provides an overview of some main techniques needed to design websites that work well on mobile devices.
## Fonts
- [Variable fonts guide](/en-US/docs/Web/CSS/CSS_fonts/Variable_fonts_guide)
- : Find out how to use variable fonts in your designs.
- [The Web Open Font Format (WOFF)](/en-US/docs/Web/CSS/CSS_fonts/WOFF)
- : WOFF (Web Open Font Format) is a font file format that is free for anyone to use on the web.
## User interface development
- [User input methods and controls](/en-US/docs/Learn/Forms/User_input_methods)
- : User input goes beyond just a mouse and keyboard: think of touchscreens for example. This article provides recommendations for managing user input and implementing controls in open web apps, along with FAQs, real-world examples, and links to further information for anyone needing more detailed information on the underlying technologies.
| 0 |
data/mdn-content/files/en-us/web/guide/css | data/mdn-content/files/en-us/web/guide/css/css_layout/index.md | ---
title: CSS Layout
slug: Web/Guide/CSS/CSS_Layout
page-type: guide
---
There are a number of methods that you can use to lay out your web pages and applications. MDN contains a number of in-depth guides to the different methods, and this page provides an overview of them all.
## Normal flow, block, and inline layout
If you are not using a flex or grid layout, then your content is laid out using normal flow, or block and inline layout. These guides will help you to understand the way this layout method works.
- [Block and Inline layout in normal flow](/en-US/docs/Web/CSS/CSS_flow_layout/Block_and_inline_layout_in_normal_flow)
- : An introduction to normal flow.
- [In flow and Out of flow](/en-US/docs/Web/CSS/CSS_flow_layout/In_flow_and_out_of_flow)
- : How to take an item out of flow, and what that does to the layout of your document.
- [Formatting contexts explained](/en-US/docs/Web/CSS/CSS_flow_layout/Introduction_to_formatting_contexts)
- : An introduction to creating a new formatting context.
- [Flow layout and writing modes](/en-US/docs/Web/CSS/CSS_flow_layout/Flow_layout_and_writing_modes)
- : How flow layout works if you use a different writing mode, such as vertical text.
- [Flow layout and overflow](/en-US/docs/Web/CSS/CSS_flow_layout/Flow_layout_and_overflow)
- : Understanding and managing overflow.
- [Introduction to the CSS basic box model](/en-US/docs/Web/CSS/CSS_box_model/Introduction_to_the_CSS_box_model)
- : Understanding the box model is a CSS fundamental; this guide explains how it works.
- [Mastering margin collapsing](/en-US/docs/Web/CSS/CSS_box_model/Mastering_margin_collapsing)
- : Find out why you sometimes end up with less margin than you expect, due to margin collapsing in normal flow.
- [Understanding CSS z-index](/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index)
- : Absolute positioning, flexbox, and grid all result in the stack (elements' relative position on the z-axis) to be manipulable via the `z-index` property. This article explains how to manage it.
## Multi-column layout
Multi-column layout, often referred to as multicol, takes content in normal flow, and breaks it into columns. Find out how to use this layout method in the following guides.
- [Basic concepts of Multicol](/en-US/docs/Web/CSS/CSS_multicol_layout/Basic_concepts)
- : An overview of the basic functionality of multicol.
- [Styling columns](/en-US/docs/Web/CSS/CSS_multicol_layout/Styling_columns)
- : There is a limited amount of styling opportunities for columns; this guide explains what you can do.
- [Spanning and balancing](/en-US/docs/Web/CSS/CSS_multicol_layout/Spanning_balancing_columns)
- : Spanning elements across columns, and balancing the content of columns.
- [Handling overflow in Multicol](/en-US/docs/Web/CSS/CSS_multicol_layout/Handling_overflow_in_multicol_layout)
- : What happens when there is more content than available column space?
- [Content breaks in Multicol](/en-US/docs/Web/CSS/CSS_multicol_layout/Handling_content_breaks_in_multicol_layout)
- : Dealing with content breaks as the content is split into columns.
## Flexbox
CSS Flexible Box Layout, commonly known as flexbox, is a layout model optimized for user interface design, and the layout of items in one dimension. In the flex layout model, the children of a flex container can be laid out in any direction, and can "flex" their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent.
- [Basic Concepts of Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Basic_concepts_of_flexbox)
- : An overview of the features of Flexbox.
- [Relationship of Flexbox to other layout methods](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Relationship_of_flexbox_to_other_layout_methods)
- : How Flexbox relates to other layout methods, and other CSS specifications.
- [Aligning items in a flex container](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Aligning_items_in_a_flex_container)
- : How the Box Alignment properties work with Flexbox.
- [Ordering flex items](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Ordering_flex_items)
- : Explaining the different ways to change the order and direction of items, and covering the potential issues in doing so.
- [Controlling Ratios of flex items along the main axis](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Controlling_ratios_of_flex_items_along_the_main_axis)
- : Explaining the `flex-grow`, `flex-shrink`, and `flex-basis` properties.
- [Mastering wrapping of flex items](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Mastering_wrapping_of_flex_items)
- : How to create flex containers with multiple lines and control the display of the items along those lines.
- [Typical use cases of Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Typical_use_cases_of_flexbox)
- : Common design patterns that are typical Flexbox use cases.
## Grid layout
CSS Grid Layout introduces a two-dimensional grid system to CSS. Grids can be used to lay out major page areas or small user interface elements.
- [Basic concepts of Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout/Basic_concepts_of_grid_layout)
- : An overview of the features of grid layout.
- [Relationship of Grid Layout to other layout methods](/en-US/docs/Web/CSS/CSS_grid_layout/Relationship_of_grid_layout_with_other_layout_methods)
- : How grid relates to other methods such as alignment, sizing, and flexbox.
- [Layout using line-based placement](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_layout_using_line-based_placement)
- : How to place items by numbered lines.
- [Grid template areas](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_template_areas)
- : How to place items using the grid-template syntax.
- [Layout using named grid lines](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_layout_using_named_grid_lines)
- : How to name lines, and place items by line name rather than number.
- [Auto-placement in CSS Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout/Auto-placement_in_grid_layout)
- : How to manage the auto-placement algorithm, and understand how the browser places items.
- [Box alignment in CSS Grid Layout](/en-US/docs/Web/CSS/CSS_grid_layout/Box_alignment_in_grid_layout)
- : How to align items, and distribute space on both axes in grid.
- [CSS Grid, Logical Values and Writing Modes](/en-US/docs/Web/CSS/CSS_grid_layout/Grids_logical_values_and_writing_modes)
- : How to use flow relative, rather than physical, properties and values with grid.
- [CSS Grid Layout and accessibility](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_layout_and_accessibility)
- : Some accessibility considerations when working with grid layout.
- [CSS Grid and progressive enhancement](/en-US/docs/Web/CSS/CSS_grid_layout/Grid_layout_and_progressive_enhancement)
- : How to ensure your site still works well in browsers that don't support grid.
- [Realizing common layouts using CSS Grid](/en-US/docs/Web/CSS/CSS_grid_layout/Realizing_common_layouts_using_grids)
- : Using grid to build some common layouts.
- [Subgrid](/en-US/docs/Web/CSS/CSS_grid_layout/Subgrid)
- : An explanation of the subgrid value, part of Grid Level 2.
- [Masonry Layout](/en-US/docs/Web/CSS/CSS_grid_layout/Masonry_layout) {{experimental_inline}}
- : An explanation of the masonry layout feature in Grid Level 3.
## Alignment
- [Box alignment in block layout](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_block_abspos_tables)
- : The alignment properties are specified for block and inline layout, though there is no browser support as yet.
- [Box alignment in flexbox](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_flexbox)
- : The alignment properties first appeared with flexbox; this guide explains how they work.
- [Box alignment in grid layout](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_grid_layout)
- : How to align items in grid layout.
- [Box alignment in multi-column layout](/en-US/docs/Web/CSS/CSS_box_alignment/Box_alignment_in_multi-column_layout)
- : How alignment will work in multicol.
| 0 |
data/mdn-content/files/en-us/web/guide/css/getting_started | data/mdn-content/files/en-us/web/guide/css/getting_started/challenge_solutions/index.md | ---
title: Challenge solutions
slug: Web/Guide/CSS/Getting_started/Challenge_solutions
page-type: guide
---
This page provides solutions to the challenges posed in the [CSS Getting Started](/en-US/docs/Learn/CSS/First_steps) tutorial. These are not the only possible solutions. The sections below correspond to the titles of the tutorial sections.
## Why use CSS
The challenges on page [Why use CSS](/en-US/docs/Learn/CSS/First_steps/How_CSS_works) are:
### Colors
- Challenge
- : Without looking up a reference, find five more color names that work in your stylesheet.
- Solution
- : CSS supports common color names like `orange`, `yellow`, `blue`, `green`, or `black`. It also supports some more exotic color names like `chartreuse`, `fuschia`, or `burlywood`. See [CSS Color value](/en-US/docs/Web/CSS/color_value) for a complete list as well as other ways of specifying colors.
## How CSS works
The challenges on page [How CSS works](/en-US/docs/Learn/CSS/First_steps/How_CSS_works) are:
### DOM inspector
- Challenge
- : In DOMi, click on a STRONG node. Use DOMi's right-hand pane to find out where the node's color is set to red, and where its appearance is made bolder than normal text.
- Solution
- : In the menu above the right-hand pane, choose **CSS Rules**. You see two items listed, one that references an internal resource and one that references your stylesheet file. The internal resource defines the **font-weight** property as `bolder`; your stylesheet defines the **color** property as `red`.
## Cascading and inheritance
The challenges on page [Cascading and inheritance](/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance) are:
### Inherited styles
- Challenge
- : Change your stylesheet so that only the red letters are underlined.
- Solution
- : Move the declaration for underlining from the rule for {{ HTMLElement("p") }} to the one for {{ HTMLElement("strong") }}. The resulting file looks like this:
```css
p {
color: blue;
}
strong {
color: orange;
text-decoration: underline;
}
```
Later sections of this tutorial describe style rules and declarations in greater detail.
## Selectors
The challenges on page [Selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) are:
### Second paragraph blue
- Challenge
- : Without changing your HTML file, add a single rule to your CSS file that keeps all the initial letters the same color as they are now, but makes all the other text in the second paragraph blue.
- Solution
- : Add a rule with an ID selector of `#second` and a declaration `color: blue;`, as shown below:
```css
#second {
color: blue;
}
```
A more specific selector, `p#second` also works.
### Both paragraphs blue
- Challenge
- : Now change the rule you have just added (without changing anything else), to make the first paragraph blue too.
- Solution
- : Change the selector of the new rule to be a tag selector using `p`:
```css
p {
color: blue;
}
```
The rules for the other colors all have more specific selectors, so they override the blue of the paragraph.
## Readable CSS
### Commenting out a rule
- Challenge
- : Comment out part of your stylesheet, without changing anything else, to make the very first letter of your document red.
- Solution
- : One way to do this is to put comment delimiters around the rule for `.carrot`:
```css
/*
.carrot {
color: orange;
}
*/
```
## Text styles
### Big initial letters
- Challenge
- : Without changing anything else, make all six initial letters twice the size in the browser's default serif font.
- Solution
- : Add the following style declaration to the `strong` rule:
```css
font: 200% serif;
```
If you use separate declarations for `font-size` and `font-family`, then the `font-style` setting on the first paragraph is _not_ overridden.
## Color
### Three-digit color codes
- Challenge
- : In your CSS file, change all the color names to 3-digit color codes without affecting the result.
- Solution
- : The following values are reasonable approximations of the named colors:
```css
strong {
color: #f00; /* red */
background-color: #ddf; /* pale blue */
font: 200% serif;
}
.carrot {
color: #fa0; /* orange */
}
.spinach {
color: #080; /* dark green */
}
p {
color: #00f; /* blue */
}
```
## Content
The challenges on page are:
### Add an image
- Challenge
- : Add a one rule to your stylesheet so that it displays the image at the start of each line.
- Solution
- : Add this rule to your stylesheet:
```css
p::before {
content: url("yellow-pin.png");
}
```
## Lists
The challenges on page [Lists](/en-US/docs/Learn/CSS/Styling_text/Styling_lists) are:
### Lower Roman numerals
- Challenge
- : Add a rule to your stylesheet, to number the oceans using Roman numerals from i to v.
- Solution
- : Define a rule for list items to use the `lower-roman` list style:
```css
li {
list-style: lower-roman;
}
```
### Capital letters
- Challenge
- : Change your stylesheet to identify the headings with capital letters in parentheses.
- Solution
- : Add a rule to the body element (parent of the headings) to reset a new counter, and one to display and increment the counter on the headings:
```css
/* numbered headings */
body {
counter-reset: headnum;
}
h3::before {
content: "(" counter(headnum, upper-latin) ") ";
counter-increment: headnum;
}
```
## Boxes
The challenges on page [Boxes](/en-US/docs/Learn/CSS/Building_blocks) are:
### Ocean border
- Challenge
- : Add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea.
- Solution
- : The following rule achieves this effect:
```css
ul {
border: 10px solid lightblue;
width: 100px;
}
```
## Layout
The challenges on page [Layout](/en-US/docs/Learn/CSS/CSS_layout) are:
### Default image position
### Fixed image position
- Challenge
- : Change your sample document, `doc2.html`, adding this tag to it near the end, just before `</BODY>`: `<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin">` Predict where the image will appear in your document. Then refresh your browser to see if you were correct.
- Solution
- : The image appears to the right of the second list.

- Challenge
- : Add a rule to your stylesheet that places the image in the top right of your document.
- Solution
- : The following rule achieves the desired result:
```css
#fixed-pin {
position: fixed;
top: 3px;
right: 3px;
}
```
## Tables
The challenges on page [Tables](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables) are:
### Borders on data cells only
- Challenge
- : Change the stylesheet to make the table have a green border around only the data cells.
- Solution
- : The following rule puts borders around only {{ HTMLElement("td") }} elements that are inside the {{ HTMLElement("tbody") }} element of the table with `id=demo-table`:
```css
#demo-table tbody td {
border: 1px solid #7a7;
}
```
## Media
The challenges on page [Media](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) are:
### Separate print style file
- Challenge
- : Move the print-specific style rules to a separate CSS file and import them into your `style4.css` stylesheet.
- Solution
- : Cut and paste the lines between `/* print only */` and `/* end print only */` into a file named `style4_print.css`. In style4.css, add the following line at the beginning of the file:
```css
@import url("style4_print.css") print;
```
### Heading hover color
- Challenge
- : Make the headings turn blue when the mouse pointer is over them.
- Solution
- : The following rule achieves the desired result:
```css
h1:hover {
color: blue;
}
```
## JavaScript
### Move box to the right
- Challenge
- : Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards.
- Solution
- : Add lines to modify the `margin-left` property. Be sure to specify it as `marginLeft` in JavaScript. The following script achieves the desired result:
```js
// JavaScript demonstration
function doDemo(button) {
const square = document.getElementById("square");
square.style.backgroundColor = "#fa4";
square.style.marginLeft = "20em";
button.setAttribute("disabled", "true");
setTimeout(clearDemo, 2000, button);
}
function clearDemo(button) {
const square = document.getElementById("square");
square.style.backgroundColor = "transparent";
square.style.marginLeft = "0em";
button.removeAttribute("disabled");
}
```
## SVG and CSS
### Change color of inner petals
- Challenge
- : Change the stylesheet so that the inner petals all turn pink when the mouse pointer is over any one of them, without changing the way the outer petals work.
- Solution
- : Move the position of the :hover pseudo-class from a specific petal, to all petals
```css
#inner-petals {
--segment-fill-fill-hover: pink;
}
/* Non-standard way for some older browsers */
#inner-petals:hover .segment-fill {
fill: pink;
stroke: none;
}
```
| 0 |
data/mdn-content/files/en-us/web | data/mdn-content/files/en-us/web/accessibility/index.md | ---
title: Accessibility
slug: Web/Accessibility
page-type: landing-page
---
<section id="Quick_links">
{{ListSubpagesForSidebar("Web/Accessibility", 1)}}
</section>
**Accessibility** (often abbreviated to **A11y** — as in, "a", then 11 characters, and then "y") in web development means enabling as many people as possible to use websites, even when those people's abilities are limited in some way.
For many people, technology makes things easier. For people with disabilities, technology makes things possible. Accessibility means developing content to be as accessible as possible, no matter an individual's physical and cognitive abilities and how they access the web.
"**The Web is fundamentally designed to work for all people**, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability." ([W3C - Accessibility](https://www.w3.org/standards/webdesign/accessibility))
## Key tutorials
The MDN [Accessibility Learning Area](/en-US/docs/Learn/Accessibility) contains modern, up-to-date tutorials covering the following accessibility essentials:
- [What is accessibility?](/en-US/docs/Learn/Accessibility/What_is_accessibility)
- : This article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the Web, and how we can make accessibility part of our web development workflow.
- [HTML: A good basis for accessibility](/en-US/docs/Learn/Accessibility/HTML)
- : A great deal of web content can be made accessible just by making sure that the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.
- [CSS and JavaScript accessibility best practices](/en-US/docs/Learn/Accessibility/CSS_and_JavaScript)
- : CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences. They can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure that even complex content is as accessible as possible.
- [WAI-ARIA basics](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics)
- : Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
- [Accessible multimedia](/en-US/docs/Learn/Accessibility/Multimedia)
- : Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so that they can be understood by assistive technologies and their users. This article shows how.
- [Mobile accessibility](/en-US/docs/Learn/Accessibility/Mobile)
- : With web access on mobile devices being so popular and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
## Other documentation
- [Understanding the Web Content Accessibility Guidelines](/en-US/docs/Web/Accessibility/Understanding_WCAG)
- : This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).
- [Introduction to color and accessibility](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance)
- : This article discusses our perception of light and color, provides a foundation for the use of color in accessible designs, and demonstrates best practices for visual and readable content.
- [Keyboard-navigable JavaScript widgets](/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets)
- : Until now, web developers who wanted to make their styled `<div>` and `<span>` based widgets accessible have lacked proper techniques. **Keyboard accessibility** is part of the minimum accessibility requirements, which a developer should be aware of.
- [ARIA](/en-US/docs/Web/Accessibility/ARIA)
- : This is a collection of articles to learn how to use Accessible Rich Internet Applications (ARIA) to make your HTML documents more accessible.
- [Mobile accessibility checklist](/en-US/docs/Web/Accessibility/Mobile_accessibility_checklist)
- : This article provides a concise checklist of accessibility requirements for mobile app developers.
- [Cognitive accessibility](/en-US/docs/Web/Accessibility/Cognitive_accessibility)
- : This article explains how to ensure that the web content you're creating is accessible to people with cognitive impairments.
- [Accessibility for seizure disorders](/en-US/docs/Web/Accessibility/Seizure_disorders)
- : Some types of visual web content can induce seizures in people with certain brain disorders. This article helps you understand the types of content that can be problematic and find tools and strategies to help you avoid them.
## See also
- [WAI Interest Group](https://www.w3.org/WAI/about/groups/waiig/)
- [Developer guides](/en-US/docs/Web/Guide)
| 0 |
data/mdn-content/files/en-us/web/accessibility | data/mdn-content/files/en-us/web/accessibility/an_overview_of_accessible_web_applications_and_widgets/index.md | ---
title: An overview of accessible web applications and widgets
slug: Web/Accessibility/An_overview_of_accessible_web_applications_and_widgets
page-type: guide
---
<section id="Quick_links">
{{ListSubpagesForSidebar("Web/Accessibility", 1)}}
</section>
Most JavaScript libraries offer a library of client-side widgets that mimic the behavior of familiar desktop interfaces. Sliders, menu bars, file list views, and more can be built with a combination of JavaScript, CSS, and HTML. Since the HTML4 specification doesn't provide built-in tags that semantically describe these kinds of widgets, developers typically resort to using generic elements such as {{HTMLElement('div')}} and {{HTMLElement('span')}}. While this results in a widget that looks like its desktop counterpart, there usually isn't enough semantic information in the markup to be usable by an assistive technology.
## The problem
Dynamic content on a web page can be particularly problematic for users who, for whatever reason, are unable to view the screen. Stock tickers, live twitter feed updates, progress indicators, and similar content modify the DOM in ways that an assistive technology (AT) may not be aware of. That's where [ARIA](/en-US/docs/Web/Accessibility/ARIA) comes in.
_Example 1: Markup for a tabs widget built without ARIA labeling. There's no information in the markup to describe the widget's form and function._
```html
<!-- This is a tabs widget. How would you know, looking only at the markup? -->
<ol>
<li id="ch1Tab">
<a href="#ch1Panel">Chapter 1</a>
</li>
<li id="ch2Tab">
<a href="#ch2Panel">Chapter 2</a>
</li>
<li id="quizTab">
<a href="#quizPanel">Quiz</a>
</li>
</ol>
<div>
<div id="ch1Panel">Chapter 1 content goes here</div>
<div id="ch2Panel">Chapter 2 content goes here</div>
<div id="quizPanel">Quiz content goes here</div>
</div>
```
_Example 2: How the tabs widget might be styled visually. Users might recognize it visually, but there are no machine-readable semantics for an assistive technology._ 
## ARIA
**ARIA** enables developers to describe their widgets in more detail by adding special attributes to the markup. Designed to fill the gap between standard HTML tags and the desktop-style controls found in dynamic web applications, ARIA provides roles and states that describe the behavior of most familiar UI widgets.
> **Warning:** Many of these were later added when browsers didn't fully support modern HTML features. **Developers should always prefer using the correct semantic HTML element over using ARIA**.
The ARIA specification is split up into three different types of attributes: roles, states, and properties. Roles describe widgets that aren't otherwise available in HTML 4, such as sliders, menu bars, tabs, and dialogs. Properties describe characteristics of these widgets, such as if they are draggable, have a required element, or have a popup associated with them. States describe the current interaction state of an element, informing the assistive technology if it is busy, disabled, selected, or hidden.
ARIA attributes are interpreted automatically by the browser and translated to the operating system's native accessibility APIs. So an element with role="slider" will be controlled in the same way as a native slider is controlled on the operating system.
This provides a much more consistent user experience than was possible in the previous generation of web applications, since assistive technology users can apply all of their knowledge of how desktop applications work when they are using web-based applications.
_Example 3: Markup for the tabs widget with ARIA attributes added._
```html
<!-- Now *these* are Tabs! -->
<!-- We've added role attributes to describe the tab list and each tab. -->
<ol role="tablist">
<li id="ch1Tab" role="tab">
<a href="#ch1Panel">Chapter 1</a>
</li>
<li id="ch2Tab" role="tab">
<a href="#ch2Panel">Chapter 2</a>
</li>
<li id="quizTab" role="tab">
<a href="#quizPanel">Quiz</a>
</li>
</ol>
<div>
<!-- Notice the role and aria-labelledby attributes we've added to describe these panels. -->
<div id="ch1Panel" role="tabpanel" aria-labelledby="ch1Tab">
Chapter 1 content goes here
</div>
<div id="ch2Panel" role="tabpanel" aria-labelledby="ch2Tab">
Chapter 2 content goes here
</div>
<div id="quizPanel" role="tabpanel" aria-labelledby="quizTab">
Quiz content goes here
</div>
</div>
```
ARIA is [well supported](https://caniuse.com/#feat=wai-aria) by all major browsers and many assistive technologies.
### Presentational changes
Dynamic presentational changes include using CSS to change the appearance of content (such as a red border around invalid data, or changing the background color of a checked checkbox), as well as showing or hiding content.
#### State changes
ARIA provides attributes for declaring the current state of a UI widget. Examples include (but are certainly not limited to):
- `aria-checked`
- : Indicates the state of a checkbox or radio button.
- `aria-disabled`
- : Indicates that an element is visible but not editable or otherwise operable.
- `aria-grabbed`
- : Indicates the 'grabbed' state of an object in a drag-and-drop operation.
(For a full list of ARIA states, consult the [ARIA list of states and properties](https://www.w3.org/TR/wai-aria-1.1/#introstates).)
Developers should use ARIA states to indicate the state of UI widget elements and use CSS attribute selectors to alter the visual appearance based on the state changes (rather than using script to change a class name on the element).
#### Visibility changes
When content visibility is changed (i.e., an element is hidden or shown), developers should change the **`aria-hidden`** property value. The techniques described above should be used to declare CSS to visually hide an element using `display:none`.
Here is an example of a tooltip that uses **`aria-hidden`** to control the visibility of the tooltip. The example shows a simple web form with tooltips containing instructions associated with the entry fields.
In this example, the HTML for the tooltip has the form shown. Line 9 sets the **`aria-hidden`** state to `true`.
```html
<div class="text">
<label id="tp1-label" for="first">First Name:</label>
<input
type="text"
id="first"
name="first"
size="20"
aria-labelledby="tp1-label"
aria-describedby="tp1"
aria-required="false" />
<div id="tp1" class="tooltip" role="tooltip" aria-hidden="true">
Your first name is optional
</div>
</div>
```
The CSS for this markup is shown in the following code. Note that there is no custom classname used, only the status of the **`aria-hidden`** attribute on line 1.
```css
div.tooltip[aria-hidden="true"] {
display: none;
}
```
The JavaScript to update the **`aria-hidden`** property has the form shown in the following code. Note that the script only updates the **`aria-hidden`** attribute (line 2); it does not need to also add or remove a custom classname.
```js
function showTip(el) {
el.setAttribute("aria-hidden", "false");
}
```
### Role changes
ARIA allows developers to declare a semantic role for an element that otherwise offers incorrect or no semantics. The **`role`** of an element should not change. Instead, remove the original element and replace it with an element with the new **`role`**.
For example, consider an "inline edit" widget: a component that allows users to edit a piece of text in place, without switching contexts. This component has a "view" mode, in which the text is not editable, but is activatable, and an "edit" mode, in which the text can be edited. A developer might be tempted to implement the "view" mode using a read-only text {{ HTMLElement("input") }} element and setting its ARIA **`role`** to `button`, then switching to "edit" mode by making the element writable and removing the **`role`** attribute in "edit" mode (since {{ HTMLElement("input") }} elements have their own role semantics).
Do not do this. Instead, implement the "view" mode using a different element altogether, such as a {{ HTMLElement("div") }} or {{ HTMLElement("span") }} with a **`role`** of `button`, and the "edit" mode using a text {{ HTMLElement("input") }} element.
### Asynchronous content changes
> **Note:** Under construction. See also [Live Regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions)
## Keyboard navigation
Often times developers overlook support for the keyboard when they create custom widgets. To be accessible to a variety of users, all features of a web application or widget should also be controllable with the keyboard, without requiring a mouse. In practice, this usually involves following the conventions supported by similar widgets on the desktop, taking full advantage of the Tab, Enter, Spacebar, and arrow keys.
Traditionally, keyboard navigation on the web has been limited to the Tab key. A user presses Tab to focus each link, button, or form on the page in a linear order, using Shift-Tab to navigate backwards. It's a one-dimensional form of navigation—forward and back, one element at a time. On fairly dense pages, a keyboard-only user often has to press the Tab key dozens of times before accessing the needed section. Implementing desktop-style keyboard conventions on the web has the potential to significantly speed up navigation for many users.
Here's a summary of how keyboard navigation should work in an ARIA-enabled web application:
- The Tab key should provide focus to the widget as a whole. For example, tabbing to a menu bar **should NOT** put focus on the menu's first element.
- The arrow keys should allow for selection or navigation within the widget. For example, using the left and right arrow keys should move focus to the previous and next menu items.
- When the widget is not inside a form, both the Enter and Spacebar keys should select or activate the control.
- Within a form, the Spacebar key should select or activate the control, while the Enter key should submit the form's default action.
- If in doubt, mimic the standard desktop behavior of the control you are creating.
So, for the Tabs widget example above, the user should be able to navigate into and out of the widget's container (the {{HTMLElement('ol')}} in our markup) using the Tab and Shift-Tab keys. Once keyboard focus is inside the container, the arrow keys should allow the user to navigate between each tab (the {{HTMLElement('li')}} elements). From here, conventions vary from platform to platform. On Windows, the next tab should automatically be activated when the user presses the arrow keys. On macOS, the user can press either Enter or the Spacebar to activate the next tab. An in-depth tutorial for creating [Keyboard-navigable JavaScript widgets](/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets) describes how to implement this behavior with JavaScript.
## See also
- [ARIA](/en-US/docs/Web/Accessibility/ARIA)
- [Writing Keyboard-navigable JavaScript widgets](/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets)
- [WAI-ARIA Specification](https://www.w3.org/TR/wai-aria-1.1/)
- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)
| 0 |
data/mdn-content/files/en-us/web/accessibility | data/mdn-content/files/en-us/web/accessibility/accessibility_and_spacial_patterns/index.md | ---
title: Accessibility and Spacial Patterns
slug: Web/Accessibility/Accessibility_and_Spacial_Patterns
page-type: guide
---
<section id="Quick_links">
{{ListSubpagesForSidebar("Web/Accessibility", 1)}}
</section>
### Spatial Localization
NASA conducted research on the perception of color, and found that luminance contrast mattered greatly as to how colors are perceived. The two images below are from NASA research, specifically, from the article, "[Designing With Blue](https://colorusage.arc.nasa.gov/blue_2.php)"
 
"_**Spatial Localization.** Symbols which have the same luminance as their background are perceptually less securely located in space and time than are symbols with higher luminance contrast. They tend to "float" visually or be "captured" by adjacent symbols with high luminance-contrast. The phenomenon seems to be especially problematic for symbol/background combinations that differ only in the blue channel._"
### Distance between stripes
Photosensitive seizures may be caused by static images as well as animation. The mechanism for this is poorly understood, but is believed to be linked to "gamma oscillations" set up in the brain. These oscillations in the brain are a different kind of response than other kinds of neurological responses believed to cause photosensitive seizures.
Stripes and patterns are typical of the kinds of images that create problems, and stripes have been studied most closely. There's the potential for causing harm if there are more than five light-dark pairs of stripes in any orientation. They can be parallel, radial, curved or straight, and may be formed by rows of repeating elements.
In 2005, Arnold Wilkins, John Emmett, and Graham Harding evaluated the guidelines for characterizing patterned images that could precipitate seizures. They revised the guidelines to their fundamental core, and came up with a surprisingly simple, but powerful [test](https://onlinelibrary.wiley.com/doi/full/10.1111/j.1528-1167.2005.01405.x). which they published in the paper, **[Characterizing the Patterned Images That Precipitate Seizures and Optimizing Guidelines To Prevent Them](https://onlinelibrary.wiley.com/doi/full/10.1111/j.1528-1167.2005.01405.x)**
> **Note:** The steps necessary to evaluate material reduce to the following:
>
> Look at the screen:
>
> - Are there more than five stripes?
> - If so, do they last longer than 0.5 s?
> - If so, does the brightness exceed the stated limit?
> - If so, categorize the motion of the pattern.
> - Are the guidelines contravened?
>
> If so, reduce brightness.
### Text and padding
WCAG standards for contrast perception do not take into account the effect of padding. For example, blue text on a gray background is easier to perceive if it is surrounded "locally" by black than by white. There is such a thing as "local" adaptation to colors. The bottom line: padding matters.
### Math
Spatial reasoning affects Math learning; consequently, spatial relationships in how math is presented affects cognition. The web developer can do something about this in the manner in which they display math. Animation figures strongly in this arena. For example, "how" an object looks when it is rotated, from different angles, how they look sliced, and how they relate to each other in space all make a difference in an ability to understand Math in spatial terms.
### Braille
Modern technology enables non-experts to print Braille. Adobe Illustrator, for example, allows one to Typeset ADA Braille for printing out.
The ability to represent spatial patterns accurate to those who are blind is critical for accessibility. For example, knowing Braille is not enough. The Braille dots have to be spatially apart from one another so as to be readable in a "human" way. The human touch does distinguish with ease braille dots that are too close or too far apart from one another.
Space has to surround the braille character. A user of braille does not lay a finger on "top" of a braille character, the user has to move her finger over the character, in the way that a sighted person must move her eyes across text written on a page.
The nature of space can change depending upon what MIME type is being used, and its version. For example, borders on SVG can extend both inward and outward from its dimensions, or for newer versions of SVG, entirely outward from it, thus reducing the space around the SVG to enable perception.
## See also
### MDN
- [Accessibility: What users can do to browse more safely](/en-US/docs/Web/Accessibility/Accessibility:_What_users_can_to_to_browse_safely)
- [Web accessibility for seizures and physical reactions](/en-US/docs/Web/Accessibility/Seizure_disorders)
- [Web Accessibility: Understanding Colors and Luminance](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance)
### Braille
- [Part 3: A Step-by-Step Guide to Typesetting ADA Braille Correctly in Adobe Illustrator](https://www.tinkeringmonkey.com/guides/ada-signage/a-step-by-step-guide-to-typesetting-ada-braille-correctly-in-adobe-illustrator/)
- [Spatial Math in BrailleBlaster (4 of 5)](https://www.youtube.com/watch?v=yz9vefDsj1g)
### Government Literature
- [NASA: Designing With Blue](https://colorusage.arc.nasa.gov/blue_2.php)
### Math
- [Spatial Reasoning: Why Math Talk is About More Than Numbers](https://dreme.stanford.edu/news/spatial-reasoning-why-math-talk-about-more-numbers)
### Scientific Literature
- [Color constancy in context: Roles for local adaptation and levels of reference](https://jov.arvojournals.org/article.aspx?articleid=2192799)
- [Gamma oscillations and photosensitive epilepsy](https://www.sciencedirect.com/science/article/pii/S0960982217304062?via%3Dihub)
- [Characterizing the Patterned Images That Precipitate Seizures and Optimizing Guidelines To Prevent Them](https://onlinelibrary.wiley.com/doi/epdf/10.1111/j.1528-1167.2005.01405.x) Arnold Wilkins, John Emmett, and Graham Harding
#### Contributors
Heartfelt thanks to Jim Allan of the [Diagram Center](http://diagramcenter.org/) for his discussions on the topic of alternative means of education.
| 0 |
data/mdn-content/files/en-us/web/accessibility | data/mdn-content/files/en-us/web/accessibility/information_for_web_authors/index.md | ---
title: Accessibility information for web authors
slug: Web/Accessibility/Information_for_Web_authors
page-type: guide
---
<section id="Quick_links">
{{ListSubpagesForSidebar("Web/Accessibility", 1)}}
</section>
## Guidelines and Regulations
1. [<abbr>ARIA</abbr> Authoring Practices Guide (<abbr>APG</abbr>)](https://www.w3.org/WAI/ARIA/apg/)
Guide to accessibility semantics defined by the Accessible Rich Internet Application (<abbr>ARIA</abbr>) specification to create accessible web experiences. Describes how to apply accessibility semantics to common design patterns and widgets, providing design patterns and functional examples.
2. [Web Content Accessibility Guidelines (<abbr>WCAG</abbr>)](https://www.w3.org/WAI/standards-guidelines/wcag/)
Another important set of guidelines from the W3C _Web Accessibility Initiative (<abbr>WAI</abbr>)_. The European Union is looking to base their upcoming accessibility regulations on these guidelines. These guidelines are discussed on the [<abbr>WAI</abbr> interest group discussion list](https://www.w3.org/WAI/about/groups/waiig/#mailinglist).
3. [ARIA on this site](/en-US/docs/Web/Accessibility/ARIA)
<abbr>MDN</abbr> guide to all the [ARIA roles](/en-US/docs/Web/Accessibility/ARIA/Roles) and [ARIA properties](/en-US/docs/Web/Accessibility/ARIA/Attributes), including best practices, related roles and properties, and examples.
## How-to's
1. [Accessibility for frontend developers](https://accessibility.digital.gov/front-end/getting-started/)
A brief guide from the U.S. General Services administration's Technology Transformation Services covering several accessibility topics with links to "how-to" videos and to related WCAG references.
2. [Accessible Web Page Authoring](https://www.ibm.com/able/requirements/requirements/)
IBM has made their accessibility requirements that need to be met public and interactive.
### Automated Checking & Repair
Use a tool to quickly check for common errors in your browser.
- [HTML CodeSniffer](https://squizlabs.github.io/HTML_CodeSniffer/)
- [aXe](https://chrome.google.com/webstore/detail/axe/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US)
- [Lighthouse Accessibility Audit](https://developer.chrome.com/docs/lighthouse/overview/)
- [Accessibility Insights](https://accessibilityinsights.io/)
- [<abbr>WAVE</abbr>](https://wave.webaim.org/extension/)
Tools to integrate into your build process, programmatically adding accessibility tests, so you can catch errors as you develop your web application:
- [axe-core](https://github.com/dequelabs/axe-core)
- [jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y)
- [Lighthouse Audits](https://github.com/GoogleChrome/lighthouse/blob/master/docs/readme.md#using-programmatically)
- [AccessLint.js](https://github.com/accesslint/accesslint.js/tree/master)
Continuous integration tools to find accessibility issues in your GitHub pull requests:
- [AccessLint](https://www.accesslint.com/)
While best to test your web applications with real users, you can simulate color blindness, low vision, low and contrast, and zooming. You should always test your site with out a mouse and touch to test keyboard navigation. You may also want to try your site using voice commands. Try disabling your mouse and using browser extensions like [Web Disability Simulator](https://chrome.google.com/webstore/detail/web-disability-simulator/olioanlbgbpmdlgjnnampnnlohigkjla)
| 0 |
data/mdn-content/files/en-us/web/accessibility | data/mdn-content/files/en-us/web/accessibility/accessibility_colon__what_users_can_to_to_browse_safely/index.md | ---
title: "Accessibility: What users can do to browse more safely"
slug: Web/Accessibility/Accessibility:_What_users_can_to_to_browse_safely
page-type: guide
---
<section id="Quick_links">
{{ListSubpagesForSidebar("Web/Accessibility", 1)}}
</section>
This article discusses making web content accessible for those with vestibular disorders, and those who support them, by taking advantage of personalization and accessibility settings built into the operating systems. Taking advantage of personalization settings can help prevent exposure to content leading to seizures and / or other physical reactions.
## Personalization and accessibility settings
From the article, "**[Understanding Success Criterion 2.3.1: Three Flashes or Below Threshold](https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html)**"
> Flashing can be caused by the display, the computer rendering the image or by the content being rendered. The author has no control of the first two. They can be addressed by the design and speed of the display and computer
### Hardware and operating systems on many computers offer control that is not afforded to developers
The user can do much to protect himself by learning his operating system, its personalization and accessibility settings. Those in the public sector who must accommodate those with special sensitivities, should consider setting aside at least one work station and becoming familiar with its personalization and accessibility settings. Understanding personalization and accessibility settings can actually be a money-saving endeavor. One work station can be set up to accommodate both a low-vision individual (needs high-contrast) and to accommodate an individual with photosensitive susceptibilities, by, adjusting personalization and accessibility settings.
### Use modern browsers. Learn personalization and accessibility settings
Modern browsers support the CSS media feature [`prefers-reduced-motion`](/en-US/docs/Web/CSS/@media/prefers-reduced-motion). Browsers can detect whether a user has requested a reduced motion experience. The user would access this through an accessibility interface, as seen below.

CSS Transition events are supported. Examples include:
- `transitionrun`
- `transitionstart`
- `transitionend`
- `transitioncancel`
### Safari 10.1 and above (Desktop)
Do not enable Auto-Play (does not work for gifs)
#### iOS Safari 10.3 and above (Mobile and Tablet)
Select the "Reduce motion option" in OS Accessibility settings for Apple (image source: developers.google.com from Thomas Steiner's article "Move Ya! Or maybe, don't, if the user prefers-reduced-motion!"). This will not work on animated gifs; the source of the animation is self-contained within a gif and is not affected by these settings.
#### Use Reader Mode on browsers
- Enable Content Blockers; Gets rid of ads, reduces and/or removes distractions
- Enables text-to-speech
- In certain browsers, enable fonts by choice
- Enable Page Zoom
#### Turn off animated GIFs in the browser
Browsers offer much power to their users; it's just a matter of knowing where to go. Using Firefox as an example, it explains that by changing the value the **image.animation_mode** from "normal" to "none", all animated images will be blocked. To reverse it, you will have to change the value back to "normal"

#### Use browser extensions
- [Gif Blocker](https://chrome.google.com/webstore/detail/gif-blocker/ahkidgegbmbnggcnmejhobepkaphkfhl?hl=en) For Chrome, GIF Blocker is an extension available at the web store.
- [Gif Scrubber](https://chrome.google.com/webstore/detail/gif-scrubber/gbdacbnhlfdlllckelpdkgeklfjfgcmp?hl=en) Gif Scrubber is a chrome extension that allows you to control gifs like a video player. There is a GitHub repository for it at **<https://github.com/0ui/gif-scrubber>**
- [Beeline Reader](https://www.beelinereader.com/) Beeline Reader has a browser extension that allows you to set up for grayscale and Dyslexi font, among other things

### Take advantage Operating System accessibility features
Most operating systems such as Windows 10, have accessibility options that are surprisingly powerful. Usually they are quite easy to find by typing (or saying) in the word, "Accessibility" in the search finder of the operating system.
#### Turn off animations in the operating system
In the Windows 10 operating system, the user has an ability to turn off animations. This will not work on animated gifs; the source of the animation is self-contained within a gif and is not affected by these settings.

#### Grayscale
Those who have suffered traumatic brain injury (TBI) may be highly sensitive to color; it can require such a great "investment of cognitive energy" on their part, there's no energy for other daily tasks. Enabling grayscale presentation of the content reduces the cognitive workload. It may assist users with other disabilities, as well. An interesting discussion by users on the benefits of using grayscale may be found in the discussion thread, "[What is the "grayscale" setting for in accessibility options?](https://ask.metafilter.com/312049/What-is-the-grayscale-setting-for-in-accessibility-options)". Of particular interest is a user who has Photosensitive Epilepsy, and uses it when feeling "seizure-y".
Most Operating Systems have a way to let the user make an adjustment on the workstation. In the screenshot below, you can see an example of Windows 10 Accessibility Settings allowing for color filters to be selected. Grayscale is enabled when the color filters button is toggled "on"

## See also
- [Accessibility](/en-US/docs/Web/Accessibility)
- [Accessibility learning path](/en-US/docs/Learn/Accessibility)
- [Web accessibility for seizures and physical reactions](/en-US/docs/Web/Accessibility/Seizure_disorders)
- [Color vision simulation](https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/simulation/index.html)
- Discussion: "[What is the "grayscale" setting for in accessibility options?](https://ask.metafilter.com/312049/What-is-the-grayscale-setting-for-in-accessibility-options)"
### Contributors
Many, many thanks to Eric Eggert from [Knowbility;](https://knowbility.org/) for his discussions and huge help on this topic.
| 0 |
data/mdn-content/files/en-us/web/accessibility | data/mdn-content/files/en-us/web/accessibility/aria/index.md | ---
title: ARIA
slug: Web/Accessibility/ARIA
page-type: landing-page
---
<section id="Quick_links">
<ol>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/Multipart_labels">Multipart labels</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li>
<li class="toggle">
<details><summary>ARIA states and properties</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}}
</details>
</li>
<li class="toggle">
<details><summary>WAI-ARIA Roles</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}}
</details>
</li>
</ol>
</section>
Accessible Rich Internet Applications **(<abbr>ARIA</abbr>)** is a set of [roles](/en-US/docs/Web/Accessibility/ARIA/Roles) and [attributes](/en-US/docs/Web/Accessibility/ARIA/Attributes) that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities.
It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not otherwise a mechanism. For example, ARIA enables accessible JavaScript widgets, form hints and error messages, live content updates, and more.
> **Warning:** Many of these widgets are fully supported in modern browsers. **Developers should prefer using the correct semantic HTML element over using ARIA**, if such an element exists. For instance, native elements have built-in [keyboard accessibility](/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets), roles and states. However, if you choose to use ARIA, you are responsible for mimicking the equivalent browser behavior in script.
[The first rule of ARIA](https://www.w3.org/TR/using-aria/#rule1) use is "If you can use a native HTML element or attribute with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so."
> **Note:** There is a saying "No ARIA is better than bad ARIA." In [WebAim's survey of over one million home pages](https://webaim.org/projects/million/#aria), they found that Home pages with ARIA present averaged 41% more detected errors than those without ARIA. While ARIA is designed to make web pages more accessible, if used incorrectly, it can do more harm than good.
Here's the markup for a progress bar widget:
```html
<div
id="percent-loaded"
role="progressbar"
aria-valuenow="75"
aria-valuemin="0"
aria-valuemax="100"></div>
```
This progress bar is built using a {{HTMLElement("div")}}, which has no meaning. We include ARIA roles and properties to add meaning. In this example, the [`role="progressbar"`](/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role) attribute informs the browser that this element is actually a JavaScript-powered progress bar widget. The [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) and [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) attributes specify the minimum and maximum values for the progress bar, and the [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) describes the current state of it and therefore must be kept updated with JavaScript.
Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using JavaScript code like this:
```js
// Find the progress bar <div> in the DOM.
const progressBar = document.getElementById("percent-loaded");
// Set its ARIA roles and states,
// so that assistive technologies know what kind of widget it is.
progressBar.setAttribute("role", "progressbar");
progressBar.setAttribute("aria-valuemin", 0);
progressBar.setAttribute("aria-valuemax", 100);
// Create a function that can be called at any time to update
// the value of the progress bar.
function updateProgress(percentComplete) {
progressBar.setAttribute("aria-valuenow", percentComplete);
}
```
All content that is available to non-assistive technology users must be made available to assistive technologies. Similarly, no features should be included targeting assistive technology users that aren't also accessible to those not using assistive technologies. The above progressbar needs to be styled to make it look like a progressbar.
It would have been much simpler to use the native {{HTMLElement('progress')}} element instead:
```HTML
<progress id="percent-loaded" value="75" max="100">75 %</progress>
```
> **Note:** The `min` attribute is not allowed for the {{HTMLElement('progress')}} element; its minimum value is always `0`.
> **Note:** HTML landmark elements ({{HTMLElement("main")}}, {{HTMLElement("header")}}, {{HTMLElement("nav")}}, etc.) have built-in implicit ARIA roles, so there is no need to duplicate them.
## Support
Like any other web technology, there are varying degrees of support for ARIA. Support is based on the operating system and browser being used, as well as the kind of assistive technology interfacing with it. In addition, the version of the operating system, browser, and assistive technology are contributing factors. Older software versions may not support certain ARIA roles, have only partial support, or misreport its functionality.
It is also important to acknowledge that some people who rely on assistive technology are reluctant to upgrade their software, for fear of losing the ability to interact with their computer and browser. Because of this, it is important to [use semantic HTML elements](/en-US/docs/Learn/Accessibility/HTML) whenever possible, as semantic HTML has far better support for assistive technology.
It is also important to test your authored ARIA with actual assistive technology. This is because browser emulators and simulators are not really effective for testing full support. Similarly, proxy assistive technology solutions are not sufficient to fully guarantee functionality.
## References
- [ARIA roles](/en-US/docs/Web/Accessibility/ARIA/Roles)
- : Reference pages covering all the WAI-ARIA roles discussed on MDN.
- [ARIA states and properties](/en-US/docs/Web/Accessibility/ARIA/Attributes)
- : Reference pages covering all the WAI-ARIA states and properties discussed on MDN.
## Standardization efforts
- [WAI-ARIA specification](https://w3c.github.io/aria/)
- : The W3C specification itself.
- [WAI-ARIA authoring practices](https://www.w3.org/TR/wai-aria-practices-1.2/)
- : The official best practices documents how best to ARIA-ify common widgets and interactions. An excellent resource.
## ARIA for scripted widgets
- [Writing keyboard-navigable JavaScript widgets](/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets)
- : Built-in elements like {{HTMLElement("input")}}, {{HTMLElement("button")}}, etc. have built-in keyboard accessibility. If you 'fake' these with {{HTMLElement("div")}}s and ARIA, you must ensure your widgets are keyboard accessible.
- [Live regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions)
- : Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
## Videos
The following talks are a great way to understand ARIA:
[ARIA, Accessibility APIs and coding like you give a damn! – Léonie Watson](https://www.youtube.com/watch?v=qdB8SRhqvFc)
| 0 |
data/mdn-content/files/en-us/web/accessibility/aria | data/mdn-content/files/en-us/web/accessibility/aria/aria_screen_reader_implementors_guide/index.md | ---
title: ARIA Screen Reader Implementors Guide
slug: Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide
page-type: guide
---
<section id="Quick_links">
<ol>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/Multipart_labels">Multipart labels</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li>
<li class="toggle">
<details><summary>ARIA states and properties</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}}
</details>
</li>
<li class="toggle">
<details><summary>WAI-ARIA Roles</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}}
</details>
</li>
</ol>
</section>
## Live Regions
This is just a guide. Live region markup is a complex area which is somewhat open to interpretation. The following is intended to provide implementation guidance that respects screen readers developers' need to try different things. The intention is to strike a balance between providing useful guidance on how to use the markup's intended meaning while supporting live regions as an area for screen readers to innovate and compete.
### Interpreting WAI-ARIA live region markup
1. Live changes are hints: in general live region markup is provided by the author as hints, and the assistive technology may allow for global, site or even region-specific settings, as well as heuristics to help with live changes on pages that have no WAI-ARIA hints.
2. Optionally, create a second, additional queue if the user configures a second hardware channel: If there are two channels for presentation (e.g. text to speech and a Braille display), then two queues can be maintained to allow for parallel presentation. The channels could be user configured for presenting live regions based on role or politeness.
3. Busy regions: Any changes in a region marked with aria-busy="true" should not be added to the queue until that attribute is cleared.
4. Politeness (`aria-live` or from [role](/en-US/docs/Web/Accessibility/ARIA/Roles)) takes first precedence,: items should be added to the queue based on their politeness level from the aria-live property or inherited from the role (e.g. [role="log"](/en-US/docs/Web/Accessibility/ARIA/Roles/log_role) is polite by default). Assertive items are first then politeness level. Alternatively, implementations may choose to have a policy of clearing more polite items, e.g. assertive items clear any polite items from the queue.
5. Time takes second precedence: Prioritize items with the same politeness level according to when the event occurs (earlier events come first). Present items of the same politeness level in the order of what occurred first.
6. Atomic (`aria-atomic="true"`) regions with multiple changes should not be presented twice with the same content. As a new event for an atomic region is added to the queue remove an earlier event for the same region. It is probably desirable to have at least a tiny timeout before presenting atomic region changes, in order to avoid presenting the region twice for two changes that occur quickly one after the other.
7. Include labels when presenting changes: if the change occurs in something with a semantic label of some kind, speak the label. This is particularly important for changes in data cells, where the column and row headers provide important contextual information.
### Ideas for Settings and Heuristics
1. Allow for a different voice (in text-to-speech) or other varying presentational characteristics to set live changes apart.
2. When no WAI-ARIA markup is present, automatically present some changes unless the user configures all live changes to off. For example, automatically speak changes that are caused by the user's own input, as part of the context of that input.
3. Allow global settings to turn off the presentation of live changes, present all live changes, use markup, or be "smart" (use heuristics)
| 0 |
data/mdn-content/files/en-us/web/accessibility/aria | data/mdn-content/files/en-us/web/accessibility/aria/multipart_labels/index.md | ---
title: "Multipart labels: Using ARIA for labels with embedded fields inside them"
slug: Web/Accessibility/ARIA/Multipart_labels
page-type: guide
---
<section id="Quick_links">
<ol>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations">ARIA annotations</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Guides">ARIA guides</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">ARIA screen reader implementors guide</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques">Using ARIA: Roles, states, and properties</a></li>
<li><a href="/en-US/docs/Web/Accessibility/ARIA/How_to_file_ARIA-related_bugs">How to file ARIA-related bugs</a></li>
<li class="toggle">
<details><summary>ARIA states and properties</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Attributes", 1)}}
</details>
</li>
<li class="toggle">
<details><summary>WAI-ARIA Roles</summary>
{{ListSubpagesForSidebar("Web/Accessibility/ARIA/Roles", 1)}}
</details>
</li>
</ol>
</section>
## Problem
You have a form where you ask your user a question, but the answer is mentioned in the question itself. A classic example we all know from our browser settings is the setting "Delete history after x days". "Delete history after" is to the left of the textbox, x is the number, for example 21, and the word "days" follows the textbox, forming a sentence that is easy to understand.
If you're using a screen reader, have you noticed that, when you go to this setting in Firefox, it tells you "Delete history after 21 days"?, followed by the announcement that you're in a textbox, and that it contains the number 21. Isn't that cool? You do not need to navigate around to find out the unit. "Days" could easily be "months" or "years", and in many ordinary dialogs, there is no way to find this out other than navigating around with screen reviewing commands.
The solution is in an ARIA attribute called `aria-labelledby`. Its parameter is a string that consists of the IDs of the HTML elements you want to concatenate into a single accessible name.
Both `aria-labelledby` and `aria-describedby` are specified on the form element that is to be labelled, for example an `<input>` In both cases, the label for/label control bindings that may also exist are overridden by `aria-labelledby`. If on an HTML page you provide `aria-labelledby`, you should also provide a label for construct to also support older browsers that do not have ARIA support yet. With Firefox 3, your visually impaired users will automatically get better accessibility from the new attribute, but the users of older browsers are not left in the dark this way.
### Example
{{ EmbedLiveSample("Example") }}
```css hidden
body {
margin: 1rem;
}
```
```html
<input
aria-labelledby="labelShutdown shutdownTime shutdownUnit"
type="checkbox" />
<span id="labelShutdown">Shut down computer after</span>
<input
aria-labelledby="labelShutdown shutdownTime shutdownUnit"
id="shutdownTime"
type="text"
value="10" />
<span id="shutdownUnit"> minutes</span>
```
## A Note for JAWS 8 users
JAWS 8.0 has its own logic to find labels, causing it to always override the accessibleName the textbox of an HTML document gets. With JAWS 8, I have not found a way to make it to accept the label from the example above. But NVDA and Window-Eyes do it just fine, and Orca on Linux also has no problems.
> **Note:** TBD: add more compatibility info
## Can this be done without ARIA?
Community member Ben Millard has pointed out in a blog post that [controls can be embedded in labels as shown in the above example using HTML 4](https://projectcerbera.com/blog/2008/03#day24), by embedding the input into the label. Thanks for that info, Ben! It is very useful and shows that some techniques that have been available for years escape even the gurus sometimes. This technique works in Firefox; however, it doesn't currently work in many other browsers, including IE. For labels with embedded form controls, using `aria-labelledby` is still the best approach.
| 0 |
data/mdn-content/files/en-us/web/accessibility/aria | data/mdn-content/files/en-us/web/accessibility/aria/attributes/index.md | ---
title: ARIA states and properties
slug: Web/Accessibility/ARIA/Attributes
page-type: landing-page
---
This page lists reference pages covering all the <abbr>WAI-ARIA</abbr> attributes discussed on MDN.
<abbr>ARIA</abbr> attributes enable modifying an element's states and properties as defined in the accessibility tree.
> **Note:** ARIA only modifies the accessibility tree, modifying how assistive technology presents the content to your users. ARIA doesn't change anything about an element's function or behavior. When not using semantic HTML elements for their intended purpose and default functionality, you must use JavaScript to manage behavior, focus, and ARIA states.
## ARIA attribute types
There are 4 categories of ARIA states and properties:
1. ### Widget attributes
- [`aria-autocomplete`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete)
- [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked)
- [`aria-disabled`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled)
- [`aria-errormessage`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage)
- [`aria-expanded`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded)
- [`aria-haspopup`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup)
- [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden)
- [`aria-invalid`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-invalid)
- [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label)
- [`aria-level`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level)
- [`aria-modal`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal)
- [`aria-multiline`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiline)
- [`aria-multiselectable`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable)
- [`aria-orientation`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation)
- [`aria-placeholder`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-placeholder)
- [`aria-pressed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed)
- [`aria-readonly`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly)
- [`aria-required`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required)
- [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected)
- [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort)
- [`aria-valuemax`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax)
- [`aria-valuemin`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin)
- [`aria-valuenow`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow)
- [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext)
2. ### Live region attributes
- [`aria-busy`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy)
- [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live)
- [`aria-relevant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant)
- [`aria-atomic`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic)
3. ### Drag-and-Drop attributes
- [`aria-dropeffect`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-dropeffect)
- [`aria-grabbed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-grabbed)
4. ### Relationship attributes
- [`aria-activedescendant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-activedescendant)
- [`aria-colcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount)
- [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex)
- [`aria-colspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colspan)
- [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls)
- [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby)
- [`aria-description`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-description)
- [`aria-details`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details)
- [`aria-errormessage`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage)
- [`aria-flowto`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-flowto)
- [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby)
- [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns)
- [`aria-posinset`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset)
- [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount)
- [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex)
- [`aria-rowspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan)
- [`aria-setsize`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize)
## Global ARIA attributes
Some states and properties apply to all HTML elements regardless of whether an ARIA role is applied. These are defined as "Global" attributes. Global states and properties are supported by all roles and base markup elements.
Many of the above attributes are global, meaning they can be included on any element unless specifically disallowed:
- [`aria-atomic`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic)
- [`aria-busy`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy)
- [`aria-controls`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls)
- [`aria-current`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current)
- [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby)
- [`aria-description`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-description)
- [`aria-details`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details)
- [`aria-disabled`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled)
- [`aria-dropeffect`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-dropeffect)
- [`aria-errormessage`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage)
- [`aria-flowto`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-flowto)
- [`aria-grabbed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-grabbed)
- [`aria-haspopup`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup)
- [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden)
- [`aria-invalid`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-invalid)
- [`aria-keyshortcuts`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-keyshortcuts)
- [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label)
- [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby)
- [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live)
- [`aria-owns`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-owns)
- [`aria-relevant`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant)
- [`aria-roledescription`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-roledescription)
By "specifically disallowed," all the above attributes are global except for the `aria-label` and `aria-labelledby` properties, which are not allowed on elements with role [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) nor its synonym [`none`](/en-US/docs/Web/Accessibility/ARIA/Roles/none_role) role.
## States and properties defined on MDN
The following are the reference pages covering the <abbr>WAI-ARIA</abbr> states and properties discussed on <abbr>MDN</abbr>.
{{SubpagesWithSummaries}}
## See also
- [Using ARIA: roles, states, and properties](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques)
<section id="Quick_links">
1. [**<abbr>WAI-ARIA</abbr> attributes**](/en-US/docs/Web/Accessibility/ARIA/Attributes)
{{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/ARIA/Attributes")}}
</section>
| 0 |
data/mdn-content/files/en-us/web/accessibility/aria/attributes | data/mdn-content/files/en-us/web/accessibility/aria/attributes/aria-label/index.md | ---
title: aria-label
slug: Web/Accessibility/ARIA/Attributes/aria-label
page-type: aria-attribute
spec-urls: https://w3c.github.io/aria/#aria-label
---
The `aria-label` attribute defines a string value that labels an interactive element.
## Description
Sometimes the default [accessible name](https://w3c.github.io/accname/#dfn-accessible-name) of an element is missing, or does not accurately describe its contents, and there is no content visible in the DOM that can be associated with the object to give it meaning. A common example is a button containing an SVG or [icon font (which you shouldn't be using)](https://www.youtube.com/watch?v=9xXBYcWgCHA) without any text.
In cases where an interactive element has no accessible name, or an accessible name that isn't accurate, and there is no content visible in the DOM that can be referenced via the [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) attribute, the `aria-label` attribute can be used to define a string that labels the interactive element on which it is set. This provides the element with its accessible name.
```html
<button aria-label="Close" onclick="myDialog.close()">
<svg
aria-hidden="true"
focusable="false"
width="17"
height="17"
xmlns="http://www.w3.org/2000/svg">
<path
d="m.967 14.217 5.8-5.906-5.765-5.89L3.094.26l5.783 5.888L14.66.26l2.092 2.162-5.766 5.889 5.801 5.906-2.092 2.162-5.818-5.924-5.818 5.924-2.092-2.162Z"
fill="#000" />
</svg>
</button>
```
> **Note:** `aria-label` is intended for use on interactive elements, or elements made to be interactive via other ARIA declarations, when there is no appropriate text visible in the DOM that could be referenced as a label
Most content has an accessible name generated from its immediate wrapping element's text content. Accessible names can also be created by certain attributes or associated elements.
By default, a button's accessible name is the content between the opening and closing {{HTMLElement('button')}} tags, an image's accessible name is the content of its [`alt`](/en-US/docs/Web/HTML/Element/img#alt) attribute, and a form input's accessible name is the content of the associated {{HTMLElement('label')}} element.
If none of these options are available, or if the default accessible name is not appropriate, use the `aria-label` attribute to define the accessible name of an element.
`aria-label` can be used in cases where text that could label the element is _not_ visible. If there is visible text that labels an element, use [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) instead.
The purpose of `aria-label` is the same as `aria-labelledby`. Both provide an accessible name for an element. If there is no visible name for the element you can reference, use `aria-label` to provide the user with a recognizable accessible name. If the label text is available in the DOM, and referencing the DOM content and acceptable user experience, prefer to use `aria-labelledby`. Don't include both. If both are present on the same element, `aria-labelledby` will take precedence over `aria-label`.
> **Note:** While `aria-label` is allowed on any element that can have an accessible name, in practice, `aria-label` is only supported on interactive elements, widgets, landmarks, images and iframes.
The `aria-label` attribute can be used with regular, semantic HTML elements; it is not limited to elements that have an [ARIA `role`](/en-US/docs/Web/Accessibility/ARIA/Roles) assigned.
Don't "overuse" `aria-label`. For example, use visible text with `aria-describedby` or `aria-description`, not `aria-label`, to provide additional instructions or clarify the UI. Always remember, you don't need to target instructions to screen readers only; if instructions are needed, provide them to everyone (or, preferably, make your UI more intuitive).
Not all elements can be given an accessible name. Neither `aria-label` nor `aria-labelledby` should be used with non-interactive elements or inline structural role such as with `code`, `term`, or `emphasis` nor roles whose semantics will not be mapped to the accessibility API, including `presentation`, `none`, and `hidden`. The `aria-label` attribute is intended for interactive elements only. Use `aria-label` to ensure an accessible name is provided when none is visible in the DOM for all interactive elements, like links, videos, form controls, [landmark roles](/en-US/docs/Web/Accessibility/ARIA/Roles#3._landmark_roles), and [widget roles](/en-US/docs/Web/Accessibility/ARIA/Roles#2._widget_roles).
If you give your {{HTMLElement('iframe')}}s a `title`, your images an `alt` attributes, and your input's associated {{HTMLElement('label')}}s, `aria-label` is not necessary. But, if present, the `aria-label` will take precedence over the `title`, `alt` and `<label>` as your `iframe`, image, or input's accessible name, respectively.
> **Note:** The `aria-label` is only "visible" to assistive technologies. If the information is important enough to add for AT users, consider making it visible for all users.
## Values
- `<string>`
- : A string of text that will be the accessible name for the object.
## Associated interfaces
- {{domxref("Element.ariaLabel")}}
- : The [`ariaLabel`](/en-US/docs/Web/API/Element/ariaLabel) property, part of the {{domxref("Element")}} interface, reflects the value of the `aria-label` attribute.
- {{domxref("ElementInternals.ariaLabel")}}
- : The [`ariaLabel`](/en-US/docs/Web/API/ElementInternals/ariaLabel) property, part of the {{domxref("ElementInternals")}} interface, reflects the value of the `aria-label` attribute.
## Associated roles
Used in almost all roles **except** roles that can not be provided an accessible name by the author.
The `aria-label` attribute is **NOT** supported in:
- [`code`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`caption`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`deletion`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`emphasis`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`generic`](/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role)
- [`insertion`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`mark`](/en-US/docs/Web/Accessibility/ARIA/Roles/mark_role)
- [`paragraph`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`presentation`](/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role) / [`none`](/en-US/docs/Web/Accessibility/ARIA/Roles/none_role)
- [`strong`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`subscript`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`superscript`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
- [`suggestion`](/en-US/docs/Web/Accessibility/ARIA/Roles/suggestion_role)
- [`term`](/en-US/docs/Web/Accessibility/ARIA/Roles/term_role)
- [`time`](/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles)
> **Note:** The `aria-label` attribute is intended for interactive elements only. When placed on non-interactive elements, such as those listed above, it may not be read or may confuse your users as a non-interactive element that acts like an interactive one.
## Specifications
{{Specifications}}
## See also
- {{HTMLElement('label')}} element
- [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby)
- [Using HTML landmark roles to improve accessibility](/en-US/blog/aria-accessibility-html-landmark-roles/) on MDN blog (2023)
<section id="Quick_links">
<strong><a href="/en-US/docs/Web/Accessibility/ARIA/Attributes">WAI-ARIA states and properties</a></strong>
{{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/aria/Attributes")}}
</section>
| 0 |
data/mdn-content/files/en-us/web/accessibility/aria/attributes | data/mdn-content/files/en-us/web/accessibility/aria/attributes/aria-rowindextext/index.md | ---
title: aria-rowindextext
slug: Web/Accessibility/ARIA/Attributes/aria-rowindextext
page-type: aria-attribute
spec-urls: https://w3c.github.io/aria/#aria-rowindextext
---
The `aria-rowindextext` attribute defines a human-readable text alternative of `aria-rowindex`.
## Description
When you have a very long table or when you purposefully want to display just a section of a table, not all rows may be present in the DOM. When this happens, we use the [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) with an integer value to define how many rows the table (or grid) would have if all the rows were present and add the [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) property on each row and spanning cell to provide information on the row index within that larger table. When the value of `aria-rowindex` is not meaningful or does not reflect the displayed index, we can also add the `aria-rowindextext` to provide a human-readable text alternative to the `aria-rowindex` integer value.
The `aria-rowindextext` should only be included **in addition to**, not as a replacement of, the `aria-rowindex`. Some assistive technologies use the numeric row index for the purpose of keeping track of the user's position or providing alternative table navigation. The `aria-rowindextext` is useful if that integer value isn't meaningful or does not reflect the displayed index, such as a game of Chess or Battleship.
The `aria-rowindextext` is added to each {{HTMLElement('tr')}} or to elements with the `row` role. It can also be addition to cells or owned elements of each row.
## Values
- `<string>`
- The human-readable text alternative of the numeric [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex)
## Associated interfaces
- {{domxref("Element.ariaRowIndexText")}}
- : The [`ariaRowIndexText`](/en-US/docs/Web/API/Element/ariaRowIndexText) property, part of the {{domxref("Element")}} interface, reflects the value of the `aria-rowindextext` attribute.
- {{domxref("ElementInternals.ariaRowIndexText")}}
- : The [`ariaRowIndexText`](/en-US/docs/Web/API/ElementInternals/ariaRowIndexText) property, part of the {{domxref("ElementInternals")}} interface, reflects the value of the `aria-rowindextext` attribute.
## Associated roles
Used in roles:
- [`cell`](/en-US/docs/Web/Accessibility/ARIA/Roles/cell_role)
- [`row`](/en-US/docs/Web/Accessibility/ARIA/Roles/row_role)
Inherited into roles:
- [`columnheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role)
- [`gridcell`](/en-US/docs/Web/Accessibility/ARIA/Roles/gridcell_role)
- [`rowheader`](/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role)
## Specifications
{{Specifications}}
## See also
- [`aria-rowindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex)
- [`aria-rowcount`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount)
- [`aria-rowspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan)
- [`aria-colindextext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindextext)
- [`aria-colindex`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex)
<section id="Quick_links">
<strong><a href="/en-US/docs/Web/Accessibility/ARIA/Attributes">WAI-ARIA states and properties</a></strong>
{{ListSubpagesForSidebar("/en-US/docs/Web/Accessibility/aria/Attributes")}}
</section>
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.