for - JavaScript

for
===

The **`for`** statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

Try it
------

Syntax
------

```js
for (initialization; condition; afterthought)
  statement
```

`initialization` Optional

An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with `var` or `let` keywords. Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for` loop is in. Variables declared with `let` are local to the statement.

The result of this expression is discarded.

`condition` Optional

An expression to be evaluated before each loop iteration. If this expression evaluates to true, `statement` is executed. If the expression evaluates to false, execution exits the loop and goes to the first statement after the `for` construct.

This conditional test is optional. If omitted, the condition always evaluates to true.

`afterthought` Optional

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of `condition`. Generally used to update or increment the counter variable.

`statement`

A statement that is executed as long as the condition evaluates to true. You can use a block statement to execute multiple statements. To execute no statement within the loop, use an empty statement (`;`).

Examples
--------

### Using for

The following `for` statement starts by declaring the variable `i` and initializing it to `0`. It checks that `i` is less than nine, performs the two succeeding statements, and increments `i` by 1 after each pass through the loop.

```js
for (let i = 0; i < 9; i++) {
  console.log(i);
  // more statements
}
```

### Initialization block syntax

The initialization block accepts both expressions and variable declarations. However, expressions cannot use the `in` operator unparenthesized, because that is ambiguous with a `for...in` loop.

```js
for (let i = "start" in window ? window.start : 0; i < 9; i++) {
  console.log(i);
}
// SyntaxError: 'for-in' loop variable declaration may not have an initializer.
```

```js
// Parenthesize the whole initializer
for (let i = ("start" in window ? window.start : 0); i < 9; i++) {
  console.log(i);
}

// Parenthesize the `in` expression
for (let i = ("start" in window) ? window.start : 0; i < 9; i++) {
  console.log(i);
}
```

### Optional for expressions

All three expressions in the head of the `for` loop are optional. For example, it is not required to use the `initialization` block to initialize variables:

```js
let i = 0;
for (; i < 9; i++) {
  console.log(i);
  // more statements
}
```

Like the `initialization` block, the `condition` part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

```js
for (let i = 0; ; i++) {
  console.log(i);
  if (i > 3) break;
  // more statements
}
```

You can also omit all three expressions. Again, make sure to use a `break` statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

```js
let i = 0;

for (;;) {
  if (i > 3) break;
  console.log(i);
  i++;
}
```

However, in the case where you are not fully using all three expression positions — especially if you are not declaring variables with the first expression but mutating something in the upper scope — consider using a `while` loop instead, which makes the intention clearer.

```js
let i = 0;

while (i <= 3) {
  console.log(i);
  i++;
}
```

### Lexical declarations in the initialization block

Declaring a variable within the initialization block has important differences from declaring it in the upper scope, especially when creating a closure within the loop body. For example, for the code below:

```js
for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
```

It logs `0`, `1`, and `2`, as expected. However, if the variable is defined in the upper scope:

```js
let i = 0;
for (; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
```

It logs `3`, `3`, and `3`. The reason is that each `setTimeout` creates a new closure that closes over the `i` variable, but if the `i` is not scoped to the loop body, all closures will reference the same variable when they eventually get called — and due to the asynchronous nature of `setTimeout`, it will happen after the loop has already exited, causing the value of `i` in all queued callbacks' bodies to have the value of `3`.

This also happens if you use a `var` statement as the initialization, because variables declared with `var` are only function-scoped, but not lexically scoped (i.e. they can't be scoped to the loop body).

```js
for (var i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
// Logs 3, 3, 3
```

The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within the `condition` and `afterthought` parts. More precisely, `let` declarations are special-cased by `for` loops — if `initialization` is a `let` declaration, then every time, after the loop body is evaluated, the following happens:

1. A new lexical scope is created with new `let`-declared variables.
2. The binding values from the last iteration are used to re-initialize the new variables.
3. `afterthought` is evaluated in the new scope.

So re-assigning the new variables within `afterthought` does not affect the bindings from the previous iteration.

A new lexical scope is also created after `initialization`, just before `condition` is evaluated for the first time. These details can be observed by creating closures, which allow to get hold of a binding at any particular point. For example, in this code a closure created within the `initialization` section does not get updated by re-assignments of `i` in the `afterthought`:

```js
for (let i = 0, getI = () => i; i < 3; i++) {
  console.log(getI());
}
// Logs 0, 0, 0
```

This does not log "0, 1, 2", like what would happen if `getI` is declared in the loop body. This is because `getI` is not re-evaluated on each iteration — rather, the function is created once and closes over the `i` variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value of `i` actually create new variables called `i`, which `getI` does not see. A way to fix this is to re-compute `getI` every time `i` updates:

```js
for (let i = 0, getI = () => i; i < 3; i++, getI = () => i) {
  console.log(getI());
}
// Logs 0, 1, 2
```

The `i` variable inside the `initialization` is distinct from the `i` variable inside every iteration, including the first. So, in this example, `getI` returns 0, even though the value of `i` inside the iteration is incremented beforehand:

```js
for (let i = 0, getI = () => i; i < 3; ) {
  i++;
  console.log(getI());
}
// Logs 0, 0, 0
```

In fact, you can capture this initial binding of the `i` variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding of `i`.

```js
for (
  let i = 0, getI = () => i, incrementI = () => i++;
  getI() < 3;
  incrementI()
) {
  console.log(i);
}
// Logs 0, 0, 0
```

This logs "0, 0, 0", because the `i` variable in each loop evaluation is actually a separate variable, but `getI` and `incrementI` both read and write the *initial* binding of `i`, not what was subsequently declared.

### Using for without a body

The following `for` cycle calculates the offset position of a node in the `afterthought` section, and therefore it does not require the use of a `statement` section, a semicolon is used instead.

```js
function showOffsetPos(id) {
  let left = 0;
  let top = 0;
  for (
    let itNode = document.getElementById(id); // initialization
    itNode; // condition
    left += itNode.offsetLeft,
      top += itNode.offsetTop,
      itNode = itNode.offsetParent // afterthought
  ); // semicolon

  console.log(
    `Offset position of "${id}" element:
left: ${left}px;
top: ${top}px;`,
  );
}

showOffsetPos("content");

// Logs:
// Offset position of "content" element:
// left: 0px;
// top: 153px;
```

Note that the semicolon after the `for` statement is mandatory, because it stands as an empty statement. Otherwise, the `for` statement acquires the following `console.log` line as its `statement` section, which makes the `log` execute multiple times.

### Using for with two iterating variables

You can create two counters that are updated simultaneously in a for loop using the comma operator. Multiple `let` and `var` declarations can also be joined with commas.

```js
const arr = [1, 2, 3, 4, 5, 6];
for (let l = 0, r = arr.length - 1; l < r; l++, r--) {
  console.log(arr[l], arr[r]);
}
// 1 6
// 2 5
// 3 4
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-for-statement |

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

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

See also
--------

* Empty statement
* `break`
* `continue`
* `while`
* `do...while`
* `for...in`
* `for...of`


continue - JavaScript

continue
========

The **`continue`** statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

Try it
------

Syntax
------

```js
continue;
continue label;
```

`label` Optional

Identifier associated with the label of the statement.

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

In contrast to the `break` statement, `continue` does not terminate the execution of the loop entirely, but instead:

* In a `while` or `do...while` loop, it jumps back to the condition.
* In a `for` loop, it jumps to the update expression.
* In a `for...in`, `for...of`, or `for await...of` loop, it jumps to the next iteration.

The `continue` statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the innermost loop. In this case, the `continue` statement needs to be nested within this labeled statement.

A `continue` statement, with or without a following label, cannot be used at the top level of a script, module, function's body, or static initialization block, even when the function or class is further contained within a loop.

Examples
--------

### Using continue with while

The following example shows a `while` loop that has a `continue` statement that executes when the value of `i` is 3. Thus, `n` takes on the values 1, 3, 7, and 12.

```js
let i = 0;
let n = 0;

while (i < 5) {
  i++;

  if (i === 3) {
    continue;
  }

  n += i;
}
```

### Using continue with a label

In the following example, a statement labeled `checkIAndJ` contains a statement labeled `checkJ`. If `continue` is encountered, the program continues at the top of the `checkJ` statement. Each time `continue` is encountered, `checkJ` reiterates until its condition returns false. When false is returned, the remainder of the `checkIAndJ` statement is completed.

If `continue` had a label of `checkIAndJ`, the program would continue at the top of the `checkIAndJ` statement.

```js
let i = 0;
let j = 8;

checkIAndJ: while (i < 4) {
  console.log(`i: ${i}`);
  i += 1;

  checkJ: while (j > 4) {
    console.log(`j: ${j}`);
    j -= 1;

    if (j % 2 === 0) continue checkJ;
    console.log(`${j} is odd.`);
  }
  console.log(`i = ${i}`);
  console.log(`j = ${j}`);
}
```

Output:
```

i: 0

// start checkj
j: 8
7 is odd.
j: 7
j: 6
5 is odd.
j: 5
// end checkj

i = 1
j = 4

i: 1
i = 2
j = 4

i: 2
i = 3
j = 4

i: 3
i = 4
j = 4
```

### Unsyntactic continue statements

`continue` cannot be used within loops across function boundaries.

```js
for (let i = 0; i < 10; i++) {
  (() => {
    continue; // SyntaxError: Illegal continue statement: no surrounding iteration statement
  })();
}
```

When referencing a label, the labeled statement must contain the `continue` statement.

```js
label: for (let i = 0; i < 10; i++) {
  console.log(i);
}

for (let i = 0; i < 10; i++) {
  continue label; // SyntaxError: Undefined label 'label'
}
```

The labeled statement must be a loop.

```js
label: {
  for (let i = 0; i < 10; i++) {
    continue label; // SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement
  }
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-continue-statement |

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

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

See also
--------

* `break`
* label


Empty statement - JavaScript

Empty statement
===============

 An **empty statement** is used to provide no statement, although the
 JavaScript syntax would expect one.

Try it
------

Syntax
------

```js
;
```

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

 The empty statement is a semicolon (`;`) indicating that no statement will
 be executed, even if JavaScript syntax requires one.

 The opposite behavior, where you want multiple statements, but JavaScript only allows a
 single one, is possible using a block statement,
 which combines several statements into a single one.

Examples
--------

### Empty loop body

 The empty statement is sometimes used with loop statements. See the following example
 with an empty loop body:

```js
const arr = [1, 2, 3];

// Assign all array values to 0
for (let i = 0; i < arr.length; arr[i++] = 0) /\* empty statement \*/ ;

console.log(arr);
// [0, 0, 0]
```

### Unintentional usage

 It is a good idea to comment *intentional* use of the empty statement, as it is
 not really obvious to distinguish from a normal semicolon.

In the following example, the usage is probably not intentional:

```js
if (condition);      // Caution, this "if" does nothing!
  killTheUniverse(); // So this always gets executed!!!
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-empty-statement |

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

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

See also
--------

* Block statement


async function - JavaScript

async function
==============

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.

* Learn more
* See full compatibility
* Report feedback
The **`async function`** declaration creates a binding of a new async function to a given name. The `await` keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.

You can also define async functions using the `async function` expression.

Try it
------

Syntax
------

```js
async function name(param0) {
  statements
}
async function name(param0, param1) {
  statements
}
async function name(param0, param1, /\* …, \*/ paramN) {
  statements
}
```

**Note:** There cannot be a line terminator between `async` and `function`, otherwise a semicolon is automatically inserted, causing `async` to become an identifier and the rest to become a `function` declaration.

### Parameters

`name`

The function's name.

`param` Optional

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.

`statements` Optional

 The statements comprising the body of the function. The `await`
 mechanism may be used.

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

An `async function` declaration creates an `AsyncFunction` object. Each time when an async function is called, it returns a new `Promise` which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.

Async functions can contain zero or more `await` expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of `async` and `await` enables the use of ordinary `try` / `catch` blocks around asynchronous code.

**Note:** The `await` keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a `SyntaxError`.

`await` can be used on its own with JavaScript modules.

**Note:** The purpose of `async`/`await` is to simplify the syntax
 necessary to consume promise-based APIs. The behavior
 of `async`/`await` is similar to combining generators and
 promises.

 Async functions always return a promise. If the return value of an async function is
 not explicitly a promise, it will be implicitly wrapped in a promise.

For example, consider the following code:

```js
async function foo() {
  return 1;
}
```

It is similar to:

```js
function foo() {
  return Promise.resolve(1);
}
```

**Note:**

Even though the return value of an async function behaves as if it's wrapped in a `Promise.resolve`, they are not equivalent.

An async function will return a different *reference*, whereas `Promise.resolve` returns the same reference if the given value is a promise.

It can be a problem when you want to check the equality of a promise and a return value of an async function.

```js
const p = new Promise((res, rej) => {
  res(1);
});

async function asyncReturn() {
  return p;
}

function basicReturn() {
  return Promise.resolve(p);
}

console.log(p === basicReturn()); // true
console.log(p === asyncReturn()); // false
```

 The body of an async function can be thought of as being split by zero or more await
 expressions. Top-level code, up to and including the first await expression (if there is
 one), is run synchronously. In this way, an async function without an await expression
 will run synchronously. If there is an await expression inside the function body,
 however, the async function will always complete asynchronously.

For example:

```js
async function foo() {
  await 1;
}
```

It is also equivalent to:

```js
function foo() {
  return Promise.resolve(1).then(() => undefined);
}
```

 Code after each await expression can be thought of as existing in a `.then`
 callback. In this way a promise chain is progressively constructed with each reentrant
 step through the function. The return value forms the final link in the chain.

 In the following example, we successively await two promises. Progress moves through
 function `foo` in three stages.

1. The first line of the body of function `foo` is executed synchronously,
 with the await expression configured with the pending promise. Progress through
 `foo` is then suspended and control is yielded back to the function that
 called `foo`.
2. Some time later, when the first promise has either been fulfilled or rejected,
 control moves back into `foo`. The result of the first promise fulfillment
 (if it was not rejected) is returned from the await expression. Here `1` is
 assigned to `result1`. Progress continues, and the second await expression
 is evaluated. Again, progress through `foo` is suspended and control is
 yielded.
3. Some time later, when the second promise has either been fulfilled or rejected,
 control re-enters `foo`. The result of the second promise resolution is
 returned from the second await expression. Here `2` is assigned to
 `result2`. Control moves to the return expression (if any). The default
 return value of `undefined` is returned as the resolution value of the
 current promise.

```js
async function foo() {
  const result1 = await new Promise((resolve) =>
    setTimeout(() => resolve("1")),
  );
  const result2 = await new Promise((resolve) =>
    setTimeout(() => resolve("2")),
  );
}
foo();
```

 Note how the promise chain is not built-up in one go. Instead, the promise chain is
 constructed in stages as control is successively yielded from and returned to the async
 function. As a result, we must be mindful of error handling behavior when dealing with
 concurrent asynchronous operations.

 For example, in the following code an unhandled promise rejection error will be thrown,
 even if a `.catch` handler has been configured further along the promise
 chain. This is because `p2` will not be "wired into" the promise chain until
 control returns from `p1`.

```js
async function foo() {
  const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000));
  const p2 = new Promise((\_, reject) => setTimeout(() => reject("2"), 500));
  const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead.
}
foo().catch(() => {}); // Attempt to swallow all errors...
```

`async function` declarations behave similar to `function` declarations — they are hoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

Examples
--------

### Async functions and execution order

```js
function resolveAfter2Seconds() {
  console.log("starting slow promise");
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("slow");
      console.log("slow promise is done");
    }, 2000);
  });
}

function resolveAfter1Second() {
  console.log("starting fast promise");
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("fast");
      console.log("fast promise is done");
    }, 1000);
  });
}

async function sequentialStart() {
  console.log("== sequentialStart starts ==");

  // 1. Start a timer, log after it's done
  const slow = resolveAfter2Seconds();
  console.log(await slow);

  // 2. Start the next timer after waiting for the previous one
  const fast = resolveAfter1Second();
  console.log(await fast);

  console.log("== sequentialStart done ==");
}

async function sequentialWait() {
  console.log("== sequentialWait starts ==");

  // 1. Start two timers without waiting for each other
  const slow = resolveAfter2Seconds();
  const fast = resolveAfter1Second();

  // 2. Wait for the slow timer to complete, and then log the result
  console.log(await slow);
  // 3. Wait for the fast timer to complete, and then log the result
  console.log(await fast);

  console.log("== sequentialWait done ==");
}

async function concurrent1() {
  console.log("== concurrent1 starts ==");

  // 1. Start two timers concurrently and wait for both to complete
  const results = await Promise.all([
    resolveAfter2Seconds(),
    resolveAfter1Second(),
  ]);
  // 2. Log the results together
  console.log(results[0]);
  console.log(results[1]);

  console.log("== concurrent1 done ==");
}

async function concurrent2() {
  console.log("== concurrent2 starts ==");

  // 1. Start two timers concurrently, log immediately after each one is done
  await Promise.all([
    (async () => console.log(await resolveAfter2Seconds()))(),
    (async () => console.log(await resolveAfter1Second()))(),
  ]);
  console.log("== concurrent2 done ==");
}

sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"

// wait above to finish
setTimeout(sequentialWait, 4000); // after 2 seconds, logs "slow" and then "fast"

// wait again
setTimeout(concurrent1, 7000); // same as sequentialWait

// wait again
setTimeout(concurrent2, 10000); // after 1 second, logs "fast", then after 1 more second, "slow"
```

#### await and concurrency

 In `sequentialStart`, execution suspends 2 seconds for the first
 `await`, and then another second for the second `await`. The
 second timer is not created until the first has already fired, so the code finishes
 after 3 seconds.

 In `sequentialWait`, both timers are created and then `await`ed.
 The timers run concurrently, which means the code finishes in 2 rather than 3 seconds,
 i.e. the slowest timer.
 However, the `await` calls still run in series, which means the second
 `await` will wait for the first one to finish. In this case, the result of
 the fastest timer is processed after the slowest.

 If you wish to safely perform other jobs after two or more jobs run concurrently and are complete, you must await a call
 to `Promise.all()` or `Promise.allSettled()` before that job.

**Warning:** The functions `sequentialWait` and `concurrent1`
 are not functionally equivalent.

 In `sequentialWait`, if promise `fast` rejects before promise
 `slow` is fulfilled, then an unhandled promise rejection error will be
 raised, regardless of whether the caller has configured a catch clause.

 In `concurrent1`, `Promise.all` wires up the promise
 chain in one go, meaning that the operation will fail-fast regardless of the order of
 rejection of the promises, and the error will always occur within the configured
 promise chain, enabling it to be caught in the normal way.

### Rewriting a Promise chain with an async function

 An API that returns a `Promise` will result in a promise chain, and it
 splits the function into many parts. Consider the following code:

```js
function getProcessedData(url) {
  return downloadData(url) // returns a promise
    .catch((e) => downloadFallbackData(url)) // returns a promise
    .then((v) => processDataInWorker(v)); // returns a promise
}
```

it can be rewritten with a single async function as follows:

```js
async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url);
  } catch (e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}
```

Alternatively, you can chain the promise with `catch()`:

```js
async function getProcessedData(url) {
  const v = await downloadData(url).catch((e) => downloadFallbackData(url));
  return processDataInWorker(v);
}
```

 In the two rewritten versions, notice there is no `await` statement after the
 `return` keyword, although that would be valid too: The return value of an
 async function is implicitly wrapped in `Promise.resolve` - if
 it's not already a promise itself (as in the examples).

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-async-function-definitions |

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

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

See also
--------

* Functions guide
* Using promises guide
* Functions
* `AsyncFunction`
* `async function` expression
* `function`
* `function*`
* `async function*`
* `await`
* `Promise`
* Decorating async JavaScript functions on innolitics.com (2016)


export - JavaScript

export
======

The **`export`** declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the `import` declaration or dynamic import. The value of an imported binding is subject to change in the module that exports it — when a module updates the value of a binding that it exports, the update will be visible in its imported value.

In order to use the `export` declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding `type="module"` to the `<script>` tag, or by being imported by another module. Modules are automatically interpreted in strict mode.

Syntax
------

```js
// Exporting declarations
export let name1, name2/\*, … \*/; // also var
export const name1 = 1, name2 = 2/\*, … \*/; // also var, let
export function functionName() { /\* … \*/ }
export class ClassName { /\* … \*/ }
export function\* generatorFunctionName() { /\* … \*/ }
export const { name1, name2: bar } = o;
export const [ name1, name2 ] = array;

// Export list
export { name1, /\* …, \*/ nameN };
export { variable1 as name1, variable2 as name2, /\* …, \*/ nameN };
export { variable1 as "string name" };
export { name1 as default /\*, … \*/ };

// Default exports
export default expression;
export default function functionName() { /\* … \*/ }
export default class ClassName { /\* … \*/ }
export default function\* generatorFunctionName() { /\* … \*/ }
export default function () { /\* … \*/ }
export default class { /\* … \*/ }
export default function\* () { /\* … \*/ }

// Aggregating modules
export \* from "module-name";
export \* as name1 from "module-name";
export { name1, /\* …, \*/ nameN } from "module-name";
export { import1 as name1, import2 as name2, /\* …, \*/ nameN } from "module-name";
export { default, /\* …, \*/ } from "module-name";
export { default as name1 } from "module-name";
```

`nameN`

Identifier to be exported (so that it can be imported via `import` in another script). If you use an alias with `as`, the actual exported name can be specified as a string literal, which may not be a valid identifier.

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

Every module can have two different types of export, *named export* and *default export*. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.

Named exports:

```js
// export features declared elsewhere
export { myFunction2, myVariable2 };

// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() {
  // …
}
```

After the `export` keyword, you can use `let`, `const`, and `var` declarations, as well as function or class declarations. You can also use the `export { name1, name2 }` syntax to export a list of names declared elsewhere. Note that `export {}` does not export an empty object — it's a no-op declaration that exports nothing (an empty name list).

Export declarations are not subject to temporal dead zone rules. You can declare that the module exports `X` before the name `X` itself is declared.

```js
export { x };
const x = 1;
// This works, because `export` is only a declaration, but doesn't
// utilize the value of `x`.
```

Default exports:

```js
// export feature declared elsewhere as default
export { myFunction as default };
// This is equivalent to:
export default myFunction;

// export individual features as default
export default function () { /\* … \*/ }
export default class { /\* … \*/ }
```

**Note:** Names for export declarations must be distinct from each other. Having exports with duplicate names or using more than one `default` export will result in a `SyntaxError` and prevent the module from being evaluated.

The `export default` syntax allows any expression.

```js
export default 1 + 1;
```

As a special case, functions and classes are exported as *declarations*, not expressions, and these declarations can be anonymous. This means functions will be hoisted.

```js
// Works because `foo` is a function declaration,
// not a function expression
foo();

export default function foo() {
  console.log("Hi");
}

// It's still technically a declaration, but it's allowed
// to be anonymous
export default function () {
  console.log("Hi");
}
```

Named exports are useful when you need to export several values. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with `as`), but the default export can be imported with any name. For example:

```js
// file test.js
const k = 12;
export default k;
```

```js
// some other file
import m from "./test"; // note that we have the freedom to use import m instead of import k, because k was default export
console.log(m); // 12
```

You can also rename named exports to avoid naming conflicts:

```js
export { myFunction as function1, myVariable as variable };
```

You can rename a name to something that's not a valid identifier by using a string literal. For example:

```js
export { myFunction as "my-function" };
```

### Re-exporting / Aggregating

A module can also "relay" values exported from other modules without the hassle of writing two separate import/export statements. This is often useful when creating a single module concentrating various exports from various modules (usually called a "barrel module").

This can be achieved with the "export from" syntax:

```js
export { default as function1, function2 } from "bar.js";
```

Which is comparable to a combination of import and export, except that `function1` and `function2` do not become available inside the current module:

```js
import { default as function1, function2 } from "bar.js";
export { function1, function2 };
```

Most of the "import from" syntaxes have "export from" counterparts.

```js
export { x } from "mod";
export { x as v } from "mod";
export \* as ns from "mod";
```

There is also `export * from "mod"`, although there's no `import * from "mod"`. This re-exports all **named** exports from `mod` as the named exports of the current module, but the default export of `mod` is not re-exported. If there are two wildcard exports statements that implicitly re-export the same name, neither one is re-exported.

```js
// -- mod1.js --
export const a = 1;

// -- mod2.js --
export const a = 3;

// -- barrel.js --
export \* from "./mod1.js";
export \* from "./mod2.js";

// -- main.js --
import \* as ns from "./barrel.js";
console.log(ns.a); // undefined
```

Attempting to import the duplicate name directly will throw an error.

```js
import { a } from "./barrel.js";
// SyntaxError: The requested module './barrel.js' contains conflicting star exports for name 'a'
```

The following is syntactically invalid despite its import equivalent:

```js
export DefaultExport from "bar.js"; // Invalid
```

The correct way of doing this is to rename the export:

```js
export { default as DefaultExport } from "bar.js";
```

The "export from" syntax allows the `as` token to be omitted, which makes the default export still re-exported as default export.

```js
export { default, function2 } from "bar.js";
```

Examples
--------

### Using named exports

In a module `my-module.js`, we could include the following code:

```js
// module "my-module.js"
function cube(x) {
  return x \* x \* x;
}

const foo = Math.PI + Math.SQRT2;

const graph = {
  options: {
    color: "white",
    thickness: "2px",
  },
  draw() {
    console.log("From graph draw function");
  },
};

export { cube, foo, graph };
```

Then in the top-level module included in your HTML page, we could have:

```js
import { cube, foo, graph } from "./my-module.js";

graph.options = {
  color: "blue",
  thickness: "3px",
};

graph.draw(); // Logs "From graph draw function"
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
```

It is important to note the following:

* You need to include this script in your HTML with a `<script>` element of `type="module"`, so that it gets recognized as a module and dealt with appropriately.
* You can't run JS modules via a `file://` URL — you'll get CORS errors. You need to run it via an HTTP server.
### Using the default export

If we want to export a single value or to have a fallback value for your module, you could use a default export:

```js
// module "my-module.js"

export default function cube(x) {
  return x \* x \* x;
}
```

Then, in another script, it is straightforward to import the default export:

```js
import cube from "./my-module.js";
console.log(cube(3)); // 27
```

### Using export from

Let's take an example where we have the following hierarchy:

* `childModule1.js`: exporting `myFunction` and `myVariable`
* `childModule2.js`: exporting `MyClass`
* `parentModule.js`: acting as an aggregator (and doing nothing else)
* top level module: consuming the exports of `parentModule.js`

This is what it would look like using code snippets:

```js
// In childModule1.js
function myFunction() {
  console.log("Hello!");
}
const myVariable = 1;
export { myFunction, myVariable };
```

```js
// In childModule2.js
class MyClass {
  constructor(x) {
    this.x = x;
  }
}

export { MyClass };
```

```js
// In parentModule.js
// Only aggregating the exports from childModule1 and childModule2
// to re-export them
export { myFunction, myVariable } from "childModule1.js";
export { MyClass } from "childModule2.js";
```

```js
// In top-level module
// We can consume the exports from a single module since parentModule
// "collected"/"bundled" them in a single source
import { myFunction, myVariable, MyClass } from "parentModule.js";
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-exports |

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

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

See also
--------

* `import`
* JavaScript modules guide
* ES6 in Depth: Modules on hacks.mozilla.org (2015)
* ES modules: A cartoon deep-dive on hacks.mozilla.org (2018)
* Exploring JS, Ch.16: Modules by Dr. Axel Rauschmayer


for...of - JavaScript

for...of
========

The **`for...of`** statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as `Array`, `String`, `TypedArray`, `Map`, `Set`, `NodeList` (and other DOM collections), as well as the `arguments` object, generators produced by generator functions, and user-defined iterables.

Try it
------

Syntax
------

```js
for (variable of iterable)
  statement
```

`variable`

Receives a value from the sequence on each iteration. May be either a declaration with `const`, `let`, or `var`, or an assignment target (e.g. a previously declared variable, an object property, or a destructuring assignment pattern). Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for...of` loop is in.

`iterable`

An iterable object. The source of the sequence of values on which the loop operates.

`statement`

A statement to be executed on every iteration. May reference `variable`. You can use a block statement to execute multiple statements.

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

A `for...of` loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an *iteration*, and the loop is said to *iterate over the iterable*. Each iteration executes statements that may refer to the current sequence value.

When a `for...of` loop iterates over an iterable, it first calls the iterable's `[@@iterator]()` method, which returns an iterator, and then repeatedly calls the resulting iterator's `next()` method to produce the sequence of values to be assigned to `variable`.

A `for...of` loop exits when the iterator has completed (the iterator's `next()` method returns an object containing `done: true`). You may also use control flow statements to change the normal control flow. `break` exits the loop and goes to the first statement after the loop body, while `continue` skips the rest of the statements of the current iteration and proceeds to the next iteration.

If the `for...of` loop exited early (e.g. a `break` statement is encountered or an error is thrown), the `return()` method of the iterator is called to perform any cleanup.

The `variable` part of `for...of` accepts anything that can come before the `=` operator. You can use `const` to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use `let`.

```js
const iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}
// 11
// 21
// 31
```

**Note:** Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).

You can use destructuring to assign multiple local variables, or use a property accessor like `for (x.y of iterable)` to assign the value to an object property.

However, a special rule forbids using `async` as the variable name. This is invalid syntax:

```js
let async;
for (async of [1, 2, 3]); // SyntaxError: The left-hand side of a for-of loop may not be 'async'.
```

This is to avoid syntax ambiguity with the valid code `for (async of => {};;)`, which is a `for` loop.

Examples
--------

### Iterating over an Array

```js
const iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30
```

### Iterating over a string

Strings are iterated by Unicode code points.

```js
const iterable = "boo";

for (const value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"
```

### Iterating over a TypedArray

```js
const iterable = new Uint8Array([0x00, 0xff]);

for (const value of iterable) {
  console.log(value);
}
// 0
// 255
```

### Iterating over a Map

```js
const iterable = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
]);

for (const entry of iterable) {
  console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]

for (const [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3
```

### Iterating over a Set

```js
const iterable = new Set([1, 1, 2, 2, 3, 3]);

for (const value of iterable) {
  console.log(value);
}
// 1
// 2
// 3
```

### Iterating over the arguments object

You can iterate over the `arguments` object to examine all parameters passed into a function.

```js
function foo() {
  for (const value of arguments) {
    console.log(value);
  }
}

foo(1, 2, 3);
// 1
// 2
// 3
```

### Iterating over a NodeList

The following example adds a `read` class to paragraphs that are direct descendants of the `<article>` element by iterating over a `NodeList` DOM collection.

```js
const articleParagraphs = document.querySelectorAll("article > p");
for (const paragraph of articleParagraphs) {
  paragraph.classList.add("read");
}
```

### Iterating over a user-defined iterable

Iterating over an object with an `@@iterator` method that returns a custom iterator:

```js
const iterable = {
  [Symbol.iterator]() {
    let i = 1;
    return {
      next() {
        if (i <= 3) {
          return { value: i++, done: false };
        }
        return { value: undefined, done: true };
      },
    };
  },
};

for (const value of iterable) {
  console.log(value);
}
// 1
// 2
// 3
```

Iterating over an object with an `@@iterator` generator method:

```js
const iterable = {
  \*[Symbol.iterator]() {
    yield 1;
    yield 2;
    yield 3;
  },
};

for (const value of iterable) {
  console.log(value);
}
// 1
// 2
// 3
```

*Iterable iterators* (iterators with a `[@@iterator]()` method that returns `this`) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such as `for...of`.

```js
let i = 1;

const iterator = {
  next() {
    if (i <= 3) {
      return { value: i++, done: false };
    }
    return { value: undefined, done: true };
  },
  [Symbol.iterator]() {
    return this;
  },
};

for (const value of iterator) {
  console.log(value);
}
// 1
// 2
// 3
```

### Iterating over a generator

```js
function\* source() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = source();

for (const value of generator) {
  console.log(value);
}
// 1
// 2
// 3
```

### Early exiting

Execution of the `break` statement in the first loop causes it to exit early. The iterator is not finished yet, so the second loop will continue from where the first one stopped at.

```js
const source = [1, 2, 3];

const iterator = source[Symbol.iterator]();

for (const value of iterator) {
  console.log(value);
  if (value === 1) {
    break;
  }
  console.log("This string will not be logged.");
}
// 1

// Another loop using the same iterator
// picks up where the last loop left off.
for (const value of iterator) {
  console.log(value);
}
// 2
// 3

// The iterator is used up.
// This loop will execute no iterations.
for (const value of iterator) {
  console.log(value);
}
// [No output]
```

Generators implement the `return()` method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.

```js
function\* source() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = source();

for (const value of generator) {
  console.log(value);
  if (value === 1) {
    break;
  }
  console.log("This string will not be logged.");
}
// 1

// The generator is used up.
// This loop will execute no iterations.
for (const value of generator) {
  console.log(value);
}
// [No output]
```

### Difference between for...of and for...in

Both `for...in` and `for...of` statements iterate over something. The main difference between them is in what they iterate over.

The `for...in` statement iterates over the enumerable string properties of an object, while the `for...of` statement iterates over values that the iterable object defines to be iterated over.

The following example shows the difference between a `for...of` loop and a `for...in` loop when used with an `Array`.

```js
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};

const iterable = [3, 5, 7];
iterable.foo = "hello";

for (const i in iterable) {
  console.log(i);
}
// "0", "1", "2", "foo", "arrCustom", "objCustom"

for (const i in iterable) {
  if (Object.hasOwn(iterable, i)) {
    console.log(i);
  }
}
// "0" "1" "2" "foo"

for (const i of iterable) {
  console.log(i);
}
// 3 5 7
```

The object `iterable` inherits the properties `objCustom` and `arrCustom` because it contains both `Object.prototype` and `Array.prototype` in its prototype chain.

The `for...in` loop logs only enumerable properties of the `iterable` object. It doesn't log array *elements* `3`, `5`, `7` or `"hello"` because those are not *properties* — they are *values*. It logs array *indexes* as well as `arrCustom` and `objCustom`, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of how array iteration and `for...in` work.

The second loop is similar to the first one, but it uses `Object.hasOwn()` to check if the found enumerable property is the object's own, i.e. not inherited. If it is, the property is logged. Properties `0`, `1`, `2` and `foo` are logged because they are own properties. Properties `arrCustom` and `objCustom` are not logged because they are inherited.

The `for...of` loop iterates and logs *values* that `iterable`, as an array (which is iterable), defines to be iterated over. The object's *elements* `3`, `5`, `7` are shown, but none of the object's *properties* are.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-for-in-and-for-of-statements |

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

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

See also
--------

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


SyntaxError: missing formal parameter - JavaScript

SyntaxError: missing formal parameter
=====================================

 The JavaScript exception "missing formal parameter" occurs when your function
 declaration is missing valid parameters.

Message
-------
```

SyntaxError: missing formal parameter (Firefox)
SyntaxError: Unexpected number '3'. Expected a parameter pattern or a ')' in parameter list. (Safari)
SyntaxError: Unexpected string literal "x". Expected a parameter pattern or a ')' in parameter list. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 "Formal parameter" is a fancy way of saying "function parameter". Your function
 declaration is missing valid parameters. In the declaration of a function, the
 parameters must be identifiers, not any
 value like numbers, strings, or objects. Declaring functions and calling functions are
 two separate steps. Declarations require identifier as parameters, and only when calling
 (invoking) the function, you provide the values the function should use.

 In JavaScript, identifiers can contain
 only alphanumeric characters (or "$" or "\_"), and may not start with a digit. An
 identifier differs from a **string** in that a string is data, while an
 identifier is part of the code.

Examples
--------

### Provide proper function parameters

 Function parameters must be identifiers when setting up a function. All these function
 declarations fail, as they are providing values for their parameters:

```js
function square(3) {
  return number \* number;
}
// SyntaxError: missing formal parameter

function greet("Howdy") {
  return greeting;
}
// SyntaxError: missing formal parameter

function log({ obj: "value"}) {
  console.log(arg)
}
// SyntaxError: missing formal parameter
```

You will need to use identifiers in function declarations:

```js
function square(number) {
  return number \* number;
}

function greet(greeting) {
  return greeting;
}

function log(arg) {
  console.log(arg);
}
```

You can then call these functions with the arguments you like:

```js
square(2); // 4

greet("Howdy"); // "Howdy"

log({ obj: "value" }); // { obj: "value" }
```

See also
--------

* SyntaxError: redeclaration of formal parameter "x"


ReferenceError: assignment to undeclared variable "x" - JavaScript

ReferenceError: assignment to undeclared variable "x"
=====================================================

The JavaScript strict mode-only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.

Message
-------
```

ReferenceError: x is not defined (V8-based)
ReferenceError: assignment to undeclared variable x (Firefox)
ReferenceError: Can't find variable: x (Safari)
```

Error type
----------

`ReferenceError` in strict mode only.

What went wrong?
----------------

 A value has been assigned to an undeclared variable.
 In other words, there was an assignment without the `var` keyword.
 There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

Three things to note about declared and undeclared variables:

* Declared variables are constrained in the execution context in which they are declared.
 Undeclared variables are always global.
* Declared variables are created before any code is executed.
 Undeclared variables do not exist until the code assigning to them is executed.
* Declared variables are a non-configurable property of their execution context (function or global).
 Undeclared variables are configurable (e.g. can be deleted).

For more details and examples, see the `var` reference page.

 Errors about undeclared variable assignments occur in strict mode code only.
 In non-strict code, they are silently ignored.

Examples
--------

### Invalid cases

In this case, the variable "bar" is an undeclared variable.

```js
function foo() {
  "use strict";
  bar = true;
}
foo(); // ReferenceError: assignment to undeclared variable bar
```

### Valid cases

To make "bar" a declared variable, you can add a `let`, `const`, or `var` keyword in front of it.

```js
function foo() {
  "use strict";
  const bar = true;
}
foo();
```

See also
--------

* Strict mode


TypeError: can't delete non-configurable array element - JavaScript

TypeError: can't delete non-configurable array element
======================================================

 The JavaScript exception "can't delete non-configurable array element" occurs when it
 was attempted to shorten the length
 of an array, but one of the array's elements is non-configurable.

Message
-------
```

TypeError: Cannot delete property '1' of [object Array] (V8-based)
TypeError: can't delete non-configurable array element (Firefox)
TypeError: Unable to delete property. (Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 It was attempted to shorten the length
 of an array, but one of the array's elements is non-configurable.
 When shortening an array, the elements beyond the new array length will be deleted,
 which failed in this situation.

 The `configurable` attribute controls whether the property can be deleted
 from the object and whether its attributes (other than `writable`) can be
 changed.

Usually, properties in an object created by an array initializer are configurable. However, for example, when using `Object.defineProperty()`, the property isn't configurable by default.

Examples
--------

### Non-configurable properties created by Object.defineProperty

 The `Object.defineProperty()` creates non-configurable properties by
 default if you haven't specified them as configurable.

```js
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0 });
Object.defineProperty(arr, 1, { value: "1" });

arr.length = 1;
// TypeError: can't delete non-configurable array element
```

You will need to set the elements as configurable, if you intend to shorten the array.

```js
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0, configurable: true });
Object.defineProperty(arr, 1, { value: "1", configurable: true });

arr.length = 1;
```

### Sealed Arrays

 The `Object.seal()` function marks all existing elements as
 non-configurable.

```js
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);

arr.length = 1;
// TypeError: can't delete non-configurable array element
```

 You either need to remove the `Object.seal()` call, or make a copy of it.
 In case of a copy, shortening the copy of the array does not modify the original array
 length.

```js
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);

// Copy the initial array to shorten the copy
const copy = Array.from(arr);
copy.length = 1;
// arr.length === 3
```

See also
--------

* [[Configurable]]
* `length`
* `Object.defineProperty()`
* `Object.seal()`


SyntaxError: missing ) after argument list - JavaScript

SyntaxError: missing ) after argument list
==========================================

 The JavaScript exception "missing ) after argument list" occurs when there is an error
 with how a function is called. This might be a typo, a missing operator, or an unescaped
 string.

Message
-------
```

SyntaxError: missing ) after argument list (V8-based & Firefox)
SyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)
```

Error type
----------

`SyntaxError`.

What went wrong?
----------------

 There is an error with how a function is called. This might be a typo, a missing
 operator, or an unescaped string, for example.

Examples
--------

 Because there is no "+" operator to concatenate the string, JavaScript expects the
 argument for the `log` function to be just `"PI: "`. In that case,
 it should be terminated by a closing parenthesis.

```js
console.log("PI: " Math.PI);
// SyntaxError: missing ) after argument list
```

You can correct the `log` call by adding the `+` operator:

```js
console.log("PI: " + Math.PI);
// "PI: 3.141592653589793"
```

Alternatively, you can consider using a template literal, or take advantage of the fact that `console.log` accepts multiple parameters:

```js
console.log(`PI: ${Math.PI}`);
console.log("PI:", Math.PI);
```

### Unterminated strings

```js
console.log('"Java" + "Script" = \"' + "Java" + 'Script\");
// SyntaxError: missing ) after argument list
```

 Here JavaScript thinks that you meant to have `);` inside the string and
 ignores it, and it ends up not knowing that you meant the `);` to end the
 function `console.log`. To fix this, we could put a`'` after the
 "Script" string:

```js
console.log('"Java" + "Script" = "' + "Java" + 'Script"');
// '"Java" + "Script" = "JavaScript"'
```

See also
--------

* Functions guide


TypeError: can't convert BigInt to number - JavaScript

TypeError: can't convert BigInt to number
=========================================

The JavaScript exception "can't convert BigInt to number" occurs when an arithmetic operation involves a mix of `BigInt` and `Number` values.

Message
-------
```

TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based)
TypeError: BigInts have no unsigned right shift, use >> instead (V8-based)
TypeError: can't convert BigInt to number (Firefox)
TypeError: Invalid mix of BigInt and other type in addition/multiplication/…. (Safari)
TypeError: BigInt does not support >>> operator (Safari)
```

Error type
----------

`TypeError`.

What went wrong?
----------------

The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.

The error can also happen if the unsigned right shift operator (`>>>`) is used between two BigInts. In Firefox, the message is the same: "can't convert BigInt to number".

Examples
--------

### Mixing numbers and BigInts in operations

```js
const sum = 1n + 1;
// TypeError: can't convert BigInt to number
```

Instead, explicitly coerce one side to a BigInt or number.

```js
const sum = 1n + BigInt(1);
const sum2 = Number(1n) + 1;
```

### Using unsigned right shift on BigInts

```js
const a = 4n >>> 2n;
// TypeError: can't convert BigInt to number
```

Use normal right shift instead.

```js
const a = 4n >> 2n;
```

See also
--------

* `BigInt`


SyntaxError: return not in function - JavaScript

SyntaxError: return not in function
===================================

The JavaScript exception "return not in function" occurs when a `return` statement is called outside of a function.

Message
-------
```

SyntaxError: Illegal return statement (V8-based)
SyntaxError: return not in function (Firefox)
SyntaxError: Return statements are only valid inside functions. (Safari)
```

Error type
----------

`SyntaxError`.

What went wrong?
----------------

A `return` statement is called outside of a function. Maybe there are missing curly braces somewhere? The `return` statement must be in a function, because it ends function execution and specifies a value to be returned to the function caller.

Examples
--------

### Missing curly braces

```js
function cheer(score) {
  if (score === 147)
    return "Maximum!";
  }
  if (score > 100) {
    return "Century!";
  }
}

// SyntaxError: return not in function
```

The curly braces look correct at a first glance, but this code snippet is missing a `{` after the first `if` statement. Correct would be:

```js
function cheer(score) {
  if (score === 147) {
    return "Maximum!";
  }
  if (score > 100) {
    return "Century!";
  }
}
```

See also
--------

* `return`


SyntaxError: JSON.parse: bad parsing - JavaScript

SyntaxError: JSON.parse: bad parsing
====================================

 The JavaScript exceptions thrown by `JSON.parse()` occur when string failed
 to be parsed as JSON.

Message
-------
```

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
```

Error type
----------

`SyntaxError`What went wrong?
----------------

`JSON.parse()` parses a string as JSON. This string has to be valid JSON
 and will throw this error if incorrect syntax was encountered.

Examples
--------

### JSON.parse() does not allow trailing commas

Both lines will throw a SyntaxError:

```js
JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
```

Omit the trailing commas to parse the JSON correctly:

```js
JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');
```

### Property names must be double-quoted strings

You cannot use single-quotes around properties, like 'foo'.

```js
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
```

Instead write "foo":

```js
JSON.parse('{"foo": 1}');
```

### Leading zeros and decimal points

 You cannot use leading zeros, like 01, and decimal points must be followed by at least
 one digit.

```js
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data

JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data
```

Instead write just 1 without a zero and use at least one digit after a decimal point:

```js
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
```

See also
--------

* `JSON`
* `JSON.parse()`
* `JSON.stringify()`


TypeError: can't convert x to BigInt - JavaScript

TypeError: can't convert x to BigInt
====================================

The JavaScript exception "x can't be converted to BigInt" occurs when attempting to convert a `Symbol`, `null`, or `undefined` value to a `BigInt`, or if an operation expecting a BigInt parameter receives a number.

Message
-------
```

TypeError: Cannot convert null to a BigInt (V8-based)
TypeError: can't convert null to BigInt (Firefox)
TypeError: Invalid argument type in ToBigInt operation (Safari)
```

Error type
----------

`TypeError`.

What went wrong?
----------------

When using the `BigInt()` function to convert a value to a BigInt, the value would first be converted to a primitive. Then, if it's not one of BigInt, string, number, and boolean, the error is thrown.

Some operations, like `BigInt.asIntN`, require the parameter to be a BigInt. Passing in a number in this case will also throw this error.

Examples
--------

### Using BigInt() on invalid values

```js
const a = BigInt(null);
// TypeError: can't convert null to BigInt
const b = BigInt(undefined);
// TypeError: can't convert undefined to BigInt
const c = BigInt(Symbol("1"));
// TypeError: can't convert Symbol("1") to BigInt
```

```js
const a = BigInt(1);
const b = BigInt(true);
const c = BigInt("1");
const d = BigInt(Symbol("1").description);
```

**Note:** Simply coercing the value to a string or number using `String()` or `Number()` before passing it to `BigInt()` is usually not sufficient to avoid all errors. If the string is not a valid integer number string, a SyntaxError is thrown; if the number is not an integer (most notably, `NaN`), a RangeError is thrown. If the range of input is unknown, properly validate it before using `BigInt()`.

### Passing a number to a function expecting a BigInt

```js
const a = BigInt.asIntN(4, 8);
// TypeError: can't convert 8 to BigInt
const b = new BigInt64Array(3).fill(3);
// TypeError: can't convert 3 to BigInt
```

```js
const a = BigInt.asIntN(4, 8n);
const b = new BigInt64Array(3).fill(3n);
```

See also
--------

* `BigInt()` constructor


SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript

SyntaxError: a declaration in the head of a for-of loop can't have an initializer
=================================================================================

The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as `for (const i = 0 of iterable)`. This is not allowed in for-of loops.

Message
-------
```

SyntaxError: for-of loop variable declaration may not have an initializer. (V8-based)
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
SyntaxError: Cannot assign to the loop variable inside a for-of loop header. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

The head of a for...of loop contains an initializer expression. That is, a variable is declared and assigned a value `for (const i = 0 of iterable)`. This is not allowed in for-of loops. You might want a `for` loop that does allow an initializer.

Examples
--------

### Invalid for-of loop

```js
const iterable = [10, 20, 30];

for (const value = 50 of iterable) {
  console.log(value);
}

// SyntaxError: a declaration in the head of a for-of loop can't
// have an initializer
```

### Valid for-of loop

You need to remove the initializer (`value = 50`) in the head of the `for-of` loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.

```js
const iterable = [10, 20, 30];

for (let value of iterable) {
  value += 50;
  console.log(value);
}
// 60
// 70
// 80
```

See also
--------

* `for...of`
* `for...in`
* `for`


SyntaxError: identifier starts immediately after numeric literal - JavaScript

SyntaxError: identifier starts immediately after numeric literal
================================================================

 The JavaScript exception "identifier starts immediately after numeric literal" occurs
 when an identifier started with a digit. Identifiers can only start with a letter,
 underscore (\_), or dollar sign ($).

Message
-------
```

SyntaxError: Unexpected identifier after numeric literal (Edge)
SyntaxError: identifier starts immediately after numeric literal (Firefox)
SyntaxError: Unexpected number (Chrome)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 The names of variables, called identifiers, conform to certain rules,
 which your code must adhere to!

 A JavaScript identifier must start with a letter, underscore (\_), or dollar sign ($).
 They can't start with a digit! Only subsequent characters can be digits (0-9).

Examples
--------

### Variable names starting with numeric literals

Variable names can't start with numbers in JavaScript. The following fails:

```js
const 1life = "foo";
// SyntaxError: identifier starts immediately after numeric literal

const foo = 1life;
// SyntaxError: identifier starts immediately after numeric literal

alert(1.foo);
// SyntaxError: identifier starts immediately after numeric literal
```

You will need to rename your variable to avoid the leading number.

```js
const life1 = "foo";
const foo = life1;
```

See also
--------

* Lexical grammar
* Grammar and types guide


TypeError: "x" is read-only - JavaScript

TypeError: "x" is read-only
===========================

 The JavaScript strict mode-only exception
 "is read-only" occurs when a global variable or object
 property that was assigned to is a read-only property.

Message
-------
```

TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)
TypeError: "x" is read-only (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```

Error type
----------

`TypeError` in strict mode only.

What went wrong?
----------------

 The global variable or object property that was assigned to is a read-only property.
 (Technically, it is a non-writable data property.)

 This error happens only in strict mode code. In
 non-strict code, the assignment is silently ignored.

Examples
--------

### Invalid cases

 Read-only properties are not super common, but they can be created using
 `Object.defineProperty()` or `Object.freeze()`.

```js
"use strict";
const obj = Object.freeze({ name: "Elsa", score: 157 });
obj.score = 0; // TypeError

("use strict");
Object.defineProperty(this, "LUNG\_COUNT", { value: 2, writable: false });
LUNG\_COUNT = 3; // TypeError

("use strict");
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray[0]++; // TypeError
```

 There are also a few read-only properties built into JavaScript. Maybe you tried to
 redefine a mathematical constant.

```js
"use strict";
Math.PI = 4; // TypeError
```

Sorry, you can't do that.

 The global variable `undefined` is also read-only, so you can't silence the
 infamous "undefined is not a function" error by doing this:

```js
"use strict";
undefined = function () {}; // TypeError: "undefined" is read-only
```

### Valid cases

```js
"use strict";
let obj = Object.freeze({ name: "Score", points: 157 });
obj = { name: obj.name, points: 0 }; // replacing it with a new object works
```

See also
--------

* `Object.defineProperty()`
* `Object.freeze()`


SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
=============================================================================

The JavaScript exception "cannot use `??` unparenthesized within `||` and `&&` expressions" occurs when an nullish coalescing operator is used with a logical OR or logical AND in the same expression without parentheses.

Message
-------
```

SyntaxError: Unexpected token '??' (V8-based)
SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions (Firefox)
SyntaxError: Unexpected token '??'. Coalescing and logical operators used together in the same expression; parentheses must be used to disambiguate. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

The operator precedence chain looks like this:
```

|   >   &&   >   ||   >   =
|   >   ??   >   =
```

However, the precedence *between* `??` and `&&`/`||` is intentionally undefined, because the short circuiting behavior of logical operators can make the expression's evaluation counter-intuitive. Therefore, the following combinations are all syntax errors, because the language doesn't know how to parenthesize the operands:

```js
a ?? b || c;
a || b ?? c;
a ?? b && c;
a && b ?? c;
```

Instead, make your intent clear by parenthesizing either side explicitly:

```js
(a ?? b) || c;
a ?? (b && c);
```

Examples
--------

When migrating legacy code that uses `||` and `&&` for guarding against `null` or `undefined`, you may often convert it partially:

```js
function getId(user, fallback) {
  // Previously: user && user.id || fallback
  return user && user.id ?? fallback; // SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
}
```

Instead, consider parenthesizing the `&&`:

```js
function getId(user, fallback) {
  return (user && user.id) ?? fallback;
}
```

Even better, consider using optional chaining instead of `&&`:

```js
function getId(user, fallback) {
  return user?.id ?? fallback;
}
```

See also
--------

* Issue about nullish coalescing precedence in the TC39 nullish-coalescing proposal
* Nullish coalescing operator (`??`)
* Operator precedence


TypeError: cyclic object value - JavaScript

TypeError: cyclic object value
==============================

 The JavaScript exception "cyclic object value" occurs when object references were found
 in JSON. `JSON.stringify()` doesn't try
 to solve them and fails accordingly.

Message
-------
```

TypeError: Converting circular structure to JSON (V8-based)
TypeError: cyclic object value (Firefox)
TypeError: JSON.stringify cannot serialize cyclic structures. (Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 The JSON format per se doesn't support object
 references (although an IETF draft exists),
 hence `JSON.stringify()` doesn't try to solve them and fails accordingly.

Examples
--------

### Circular references

In a circular structure like the following

```js
const circularReference = { otherData: 123 };
circularReference.myself = circularReference;
```

`JSON.stringify()` will fail

```js
JSON.stringify(circularReference);
// TypeError: cyclic object value
```

 To serialize circular references you can use a library that supports them (e.g. cycle.js)
 or implement a solution by yourself, which will require finding and replacing (or
 removing) the cyclic references by serializable values.

 The snippet below illustrates how to find and filter (thus causing data loss) a cyclic
 reference by using the `replacer` parameter of
 `JSON.stringify()`:

```js
function getCircularReplacer() {
  const ancestors = [];
  return function (key, value) {
    if (typeof value !== "object" || value === null) {
      return value;
    }
    // `this` is the object that value is contained in,
    // i.e., its direct parent.
    while (ancestors.length > 0 && ancestors.at(-1) !== this) {
      ancestors.pop();
    }
    if (ancestors.includes(value)) {
      return "[Circular]";
    }
    ancestors.push(value);
    return value;
  };
}

JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123,"myself":"[Circular]"}

const o = {};
const notCircularReference = [o, o];
JSON.stringify(notCircularReference, getCircularReplacer());
// [{},{}]
```

See also
--------

* `JSON.stringify()`
* cycle.js on GitHub


InternalError: too much recursion - JavaScript

InternalError: too much recursion
=================================

 The JavaScript exception "too much recursion" or "Maximum call stack size exceeded"
 occurs when there are too many function calls, or a function is missing a base case.

Message
-------
```

RangeError: Maximum call stack size exceeded (Chrome)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded. (Safari)
```

Error type
----------

`InternalError` in Firefox; `RangeError` in Chrome and Safari.

What went wrong?
----------------

 A function that calls itself is called a *recursive function*. Once a condition
 is met, the function stops calling itself. This is called a *base case*.

 In some ways, recursion is analogous to a loop. Both execute the same code multiple
 times, and both require a condition (to avoid an infinite loop, or rather, infinite
 recursion in this case). When there are too many function calls, or a function is
 missing a base case, JavaScript will throw this error.

Examples
--------

This recursive function runs 10 times, as per the exit condition.

```js
function loop(x) {
  if (x >= 10)
    // "x >= 10" is the exit condition
    return;
  // do stuff
  loop(x + 1); // the recursive call
}
loop(0);
```

Setting this condition to an extremely high value, won't work:

```js
function loop(x) {
  if (x >= 1000000000000) return;
  // do stuff
  loop(x + 1);
}
loop(0);

// InternalError: too much recursion
```

 This recursive function is missing a base case. As there is no exit condition, the
 function will call itself infinitely.

```js
function loop(x) {
  // The base case is missing
  loop(x + 1); // Recursive call
}

loop(0);

// InternalError: too much recursion
```

### Class error: too much recursion

```js
class Person {
  constructor() {}
  set name(name) {
    this.name = name; // Recursive call
  }
}

const tony = new Person();
tony.name = "Tonisha"; // InternalError: too much recursion
```

 When a value is assigned to the property name (this.name = name;) JavaScript needs to
 set that property. When this happens, the setter function is triggered.

In this example when the setter is triggered, it is told to do the same thing again: *to set the same property that it is meant to handle.* This causes the function to call itself, again and again, making it infinitely recursive.

This issue also appears if the same variable is used in the getter.

```js
class Person {
  get name() {
    return this.name; // Recursive call
  }
}
```

 To avoid this problem, make sure that the property being assigned to inside the setter
 function is different from the one that initially triggered the setter. The same goes
 for the getter.

```js
class Person {
  constructor() {}
  set name(name) {
    this._name = name;
  }
  get name() {
    return this._name;
  }
}
const tony = new Person();
tony.name = "Tonisha";
console.log(tony);
```

See also
--------

* Recursion
* Recursive functions


SyntaxError: missing = in const declaration - JavaScript

SyntaxError: missing = in const declaration
===========================================

 The JavaScript exception "missing = in const declaration" occurs when a const
 declaration was not given a value in the same statement (like
 `const RED_FLAG;`). You need to provide one
 (`const RED_FLAG = "#ff0"`).

Message
-------
```

SyntaxError: Missing initializer in const declaration (V8-based)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Unexpected token ';'. const declared variable 'x' must have an initializer. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 A constant is a value that cannot be altered by the program during normal execution. It
 cannot change through re-assignment, and it can't be redeclared. In JavaScript,
 constants are declared using the
 `const`
 keyword. An initializer for a constant is required; that is, you must specify its value
 in the same statement in which it's declared (which makes sense, given that it can't be
 changed later).

Examples
--------

### Missing const initializer

 Unlike `var` or `let`, you must specify a value for a
 `const` declaration. This throws:

```js
const COLUMNS;
// SyntaxError: missing = in const declaration
```

### Fixing the error

 There are multiple options to fix this error. Check what was intended to be achieved
 with the constant in question.

#### Adding a constant value

Specify the constant value in the same statement in which it's declared:

```js
const COLUMNS = 80;
```

#### `const`, `let` or `var`?

 Do not use `const` if you weren't meaning to declare a constant. Maybe you
 meant to declare a block-scoped variable with
 `let` or
 global variable with
 `var`. Both
 don't require an initial value.

```js
let columns;
```

See also
--------

* `const`
* `let`
* `var`


TypeError: can't redefine non-configurable property "x" - JavaScript

TypeError: can't redefine non-configurable property "x"
=======================================================

 The JavaScript exception "can't redefine non-configurable property" occurs when it was
 attempted to redefine a property, but that property is non-configurable.

Message
-------
```

TypeError: Cannot redefine property: "x" (V8-based)
TypeError: can't redefine non-configurable property "x" (Firefox)
TypeError: Attempting to change value of a readonly property. (Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 It was attempted to redefine a property, but that property is non-configurable. The
 `configurable` attribute controls whether the property can be deleted from
 the object and whether its attributes (other than `writable`) can be changed.
 Usually, properties in an object created by an
 object initializer are configurable. However, for example, when using
 `Object.defineProperty()`, the property isn't configurable by default.

Examples
--------

### Non-configurable properties created by Object.defineProperty

 The `Object.defineProperty()` creates non-configurable properties if you
 haven't specified them as configurable.

```js
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar" });

Object.defineProperty(obj, "foo", { value: "baz" });
// TypeError: can't redefine non-configurable property "foo"
```

 You will need to set the "foo" property to configurable, if you intend to redefine it
 later in the code.

```js
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar", configurable: true });
Object.defineProperty(obj, "foo", { value: "baz", configurable: true });
```

See also
--------

* [[Configurable]]
* `Object.defineProperty()`


RangeError: repeat count must be less than infinity - JavaScript

RangeError: repeat count must be less than infinity
===================================================

 The JavaScript exception "repeat count must be less than infinity" occurs when the
 `String.prototype.repeat()` method is used with a `count`
 argument that is infinity.

Message
-------
```

RangeError: Invalid string length (V8-based)
RangeError: Invalid count value: Infinity (V8-based)
RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)
RangeError: Out of memory (Safari)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)
```

Error type
----------

`RangeError`What went wrong?
----------------

 The `String.prototype.repeat()` method has been used. It has a
 `count` parameter indicating the number of times to repeat the string. It
 must be between 0 and less than positive `Infinity` and cannot be a negative
 number. The range of allowed values can be described like this: [0, +∞).

 The resulting string can also not be larger than the maximum string size, which can
 differ in JavaScript engines. In Firefox (SpiderMonkey) the maximum string size is
 230 - 2 (~2GiB).

Examples
--------

### Invalid cases

```js
"abc".repeat(Infinity); // RangeError
"a".repeat(2 \*\* 30); // RangeError
```

### Valid cases

```js
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
```

See also
--------

* `String.prototype.repeat()`


TypeError: invalid assignment to const "x" - JavaScript

TypeError: invalid assignment to const "x"
==========================================

 The JavaScript exception "invalid assignment to const" occurs when it was attempted to
 alter a constant value. JavaScript
 `const`
 declarations can't be re-assigned or redeclared.

Message
-------
```

TypeError: Assignment to constant variable. (V8-based)
TypeError: invalid assignment to const 'x' (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 A constant is a value that cannot be altered by the program during normal execution. It
 cannot change through re-assignment, and it can't be redeclared. In JavaScript,
 constants are declared using the
 `const`
 keyword.

Examples
--------

### Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

```js
const COLUMNS = 80;

// …

COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'
```

### Fixing the error

 There are multiple options to fix this error. Check what was intended to be achieved
 with the constant in question.

#### Rename

 If you meant to declare another constant, pick another name and re-name. This constant
 name is already taken in this scope.

```js
const COLUMNS = 80;
const WIDE\_COLUMNS = 120;
```

#### const, let or var?

 Do not use const if you weren't meaning to declare a constant. Maybe you meant to
 declare a block-scoped variable with
 `let` or
 global variable with
 `var`.

```js
let columns = 80;

// …

columns = 120;
```

#### Scoping

 Check if you are in the correct scope. Should this constant appear in this scope or was
 it meant to appear in a function, for example?

```js
const COLUMNS = 80;

function setupBigScreenEnvironment() {
  const COLUMNS = 120;
}
```

### const and immutability

 The `const` declaration creates a read-only reference to a value. It does
 **not** mean the value it holds is immutable, just that the variable
 identifier cannot be reassigned. For instance, in case the content is an object, this
 means the object itself can still be altered. This means that you can't mutate the value
 stored in a variable:

```js
const obj = { foo: "bar" };
obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'
```

But you can mutate the properties in a variable:

```js
obj.foo = "baz";
obj; // { foo: "baz" }
```

See also
--------

* `const`
* `let`
* `var`


TypeError: More arguments needed - JavaScript

TypeError: More arguments needed
================================

 The JavaScript exception "more arguments needed" occurs when there is an error with how
 a function is called. More arguments need to be provided.

Message
-------
```

TypeError: Object prototype may only be an Object or null: undefined (V8-based)
TypeError: Object.create requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed (Firefox)
TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed (Firefox)
TypeError: Object prototype may only be an Object or null. (Safari)
```

Error type
----------

`TypeError`.

What went wrong?
----------------

There is an error with how a function is called. More arguments need to be provided.

Examples
--------

### Required arguments not provided

 The `Object.create()` method requires at least one argument and the
 `Object.setPrototypeOf()` method requires at least two arguments:

```js
const obj = Object.create();
// TypeError: Object.create requires at least 1 argument, but only 0 were passed

const obj2 = Object.setPrototypeOf({});
// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed
```

You can fix this by setting `null` as the prototype, for example:

```js
const obj = Object.create(null);

const obj2 = Object.setPrototypeOf({}, null);
```

See also
--------

* Functions guide


SyntaxError: illegal character - JavaScript

SyntaxError: illegal character
==============================

 The JavaScript exception "illegal character" occurs when there is an invalid or
 unexpected token that doesn't belong at this position in the code.

Message
-------
```

SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 There is an invalid or unexpected token that doesn't belong at this position in the
 code. Use an editor that supports syntax highlighting and carefully check your code
 against mismatches like a minus sign (`-`) versus a dash (`–`)
 or simple quotes (`"`) versus non-standard quotation marks (`"`).

Examples
--------

### Mismatched characters

 Some characters look similar, but will cause the parser to fail interpreting your code.
 Famous examples of this are quotes, the minus or semicolon
 (greek question mark (U+37e) looks same).

```js
“This looks like a string”; // SyntaxError: illegal character
// “ and ” are not " but look like it

42 – 13; // SyntaxError: illegal character
// – (en-dash) is not - but looks like it

const foo = "bar"; // SyntaxError: illegal character
// <37e> is not ; but looks like it
```

This should work:

```js
"This is actually a string";
42 - 13;
const foo = "bar";
```

Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.

### Forgotten characters

It's easy to forget a character here or there.

```js
const colors = ["#000", #333", "#666"];
// SyntaxError: illegal character
```

Add the missing quote for `"#333"`.

```js
const colors = ["#000", "#333", "#666"];
```

### Hidden characters

 When copy pasting code from external sources, there might be invalid characters. Watch
 out!

```js
const foo = "bar";
// SyntaxError: illegal character
```

 When inspecting this code in an editor like Vim, you can see that there is actually a
 zero-width space (ZWSP) (U+200B) character.

```js
const foo = "bar";<200b>
```

See also
--------

* Lexical grammar


SyntaxError: missing ) after condition - JavaScript

SyntaxError: missing ) after condition
======================================

 The JavaScript exception "missing ) after condition" occurs when there is an error with
 how an
 `if`
 condition is written. It must appear in parenthesis after the `if` keyword.

Message
-------
```

SyntaxError: missing ) after condition (Firefox)
SyntaxError: Unexpected token '{'. Expected ')' to end an 'if' condition. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 There is an error with how an
 `if`
 condition is written. In any programming language, code needs to make decisions and
 carry out actions accordingly depending on different inputs. The if statement executes a
 statement if a specified condition is truthy. In JavaScript, this condition must appear
 in parenthesis after the `if` keyword, like this:

```js
if (condition) {
  // do something if the condition is true
}
```

Examples
--------

### Missing parenthesis

It might just be an oversight, carefully check all you parenthesis in your code.

```js
if (Math.PI < 3 {
  console.log("wait what?");
}

// SyntaxError: missing ) after condition
```

To fix this code, you would need to add a parenthesis that closes the condition.

```js
if (Math.PI < 3) {
  console.log("wait what?");
}
```

### Misused is keyword

 If you are coming from another programming language, it is also easy to add keywords
 that don't mean the same or have no meaning at all in JavaScript.

```js
if (done is true) {
 console.log("we are done!");
}

// SyntaxError: missing ) after condition
```

 Instead you need to use a correct comparison operator.
 For example:

```js
if (done === true) {
  console.log("we are done!");
}
```

Or even better:

```js
if (done) {
  console.log("we are done!");
}
```

See also
--------

* `if...else`
* Relational operators
* Making decisions in your code — conditionals


TypeError: "x" is not a constructor - JavaScript

TypeError: "x" is not a constructor
===================================

 The JavaScript exception "is not a constructor" occurs when there was an attempt to use
 an object or a variable as a constructor, but that object or variable is not a
 constructor.

Message
-------
```

TypeError: x is not a constructor (V8-based & Firefox & Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 There was an attempt to use an object or a variable as a constructor, but that object
 or variable is not a constructor. See constructor
 or the `new` operator
 for more information on what a constructor is.

 There are many global objects, like `String` or `Array`, which
 are constructable using `new`. However, some global objects are not and their
 properties and methods are static. The following JavaScript standard built-in objects
 are not a constructor: `Math`, `JSON`, `Symbol`,
 `Reflect`, `Intl`, `Atomics`.

Generator functions cannot be used as constructors either.

Examples
--------

### Invalid cases

```js
const Car = 1;
new Car();
// TypeError: Car is not a constructor

new Math();
// TypeError: Math is not a constructor

new Symbol();
// TypeError: Symbol is not a constructor

function\* f() {}
const obj = new f();
// TypeError: f is not a constructor
```

### A car constructor

 Suppose you want to create an object type for cars. You want this type of object to be
 called `Car`, and you want it to have properties for make, model, and year.
 To do this, you would write the following function:

```js
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
```

Now you can create an object called `mycar` as follows:

```js
const mycar = new Car("Eagle", "Talon TSi", 1993);
```

### In Promises

When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a `new Promise(...)` and act on it. Instead, use the `Promise.resolve()` or `Promise.reject()` static methods.

This is not legal (the `Promise` constructor is not being called correctly) and will throw a `TypeError: this is not a constructor` exception:

```js
const fn = () => {
  return new Promise.resolve(true);
};
```

This is legal, but unnecessarily long:

```js
const fn = () => {
  return new Promise((resolve, reject) => {
    resolve(true);
  });
};
```

Instead, return the static method:

```js
const resolveAlways = () => {
  return Promise.resolve(true);
};

const rejectAlways = () => {
  return Promise.reject(false);
};
```

See also
--------

* constructor
* `new`


SyntaxError: label not found - JavaScript

SyntaxError: label not found
============================

The JavaScript exception "label not found" occurs when a `break` or `continue` statement references a label that does not exist on any statement that contains the `break` or `continue` statement.

Message
-------
```

SyntaxError: Undefined label 'label' (V8-based)
SyntaxError: label not found (Firefox)
SyntaxError: Cannot use the undeclared label 'label'. (Safari)
```

Error type
----------

`SyntaxError`.

What went wrong?
----------------

In JavaScript, labels are very limited: you can only use them with `break` and `continue` statements, and you can only jump to them from a statement contained within the labeled statement. You cannot jump to this label from anywhere in the program.

Examples
--------

### Unsyntactic jump

You cannot use labels as if they are `goto`.

```js
start: console.log("Hello, world!");
console.log("Do it again");
break start;
```

Instead, you can only use labels to enhance the normal semantics of `break` and `continue` statements.

```js
start: {
  console.log("Hello, world!");
  if (Math.random() > 0.5) {
    break start;
  }
  console.log("Maybe I'm logged");
}
```

See also
--------

* Labeled statement


SyntaxError: await is only valid in async functions, async generators and modules - JavaScript

SyntaxError: await is only valid in async functions, async generators and modules
=================================================================================

The JavaScript exception "await is only valid in async functions, async generators and modules" occurs when an `await` expression is used outside of async functions or modules or other async contexts.

Message
-------
```

SyntaxError: await is only valid in async functions and the top level bodies of modules (V8-based)
SyntaxError: await is only valid in async functions, async generators and modules (Firefox)
SyntaxError: Unexpected identifier (Safari)
```

Error type
----------

`SyntaxError`.

What went wrong?
----------------

JavaScript execution is never blocking: an `await` can never block the execution of the program. Instead, it pauses the execution of the surrounding async task, while allowing other tasks to continue running. Therefore, `await` cannot be used in sync tasks, such as functions, generator functions, or top level of scripts. It is not always apparent whether the current file is a script or a module — see the Modules guide for more information.

Examples
--------

### Top-level await

You cannot use `await` at the top level of a script:

```html
<script>
 await fetch("https://example.com");
 // SyntaxError: await is only valid in async functions, async generators and modules
</script>
```

Instead, make the script a module:

```html
<script type="module">
 await fetch("https://example.com");
</script>
```

### Async callbacks

You cannot use `await` in a sync callback:

```js
urls.forEach((url) => {
  await fetch(url);
  // SyntaxError: await is only valid in async functions, async generators and modules
});
```

Instead, make the callback async. See more explanation in the Using promises guide.

```js
Promise.all(
  urls.map(async (url) => {
    await fetch(url);
  }),
);
```

See also
--------

* `await`


SyntaxError: missing } after function body - JavaScript

SyntaxError: missing } after function body
==========================================

 The JavaScript exception "missing } after function body" occurs when there is a syntax
 mistake when creating a function somewhere. Check if any closing curly braces or
 parenthesis are in the correct order.

Message
-------
```

SyntaxError: missing } after function body (Firefox)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 There is a syntax mistake when creating a function somewhere. Also check if any closing
 curly braces or parenthesis are in the correct order. Indenting or formatting the code
 a bit nicer might also help you to see through the jungle.

Examples
--------

### Forgotten closing curly bracket

Oftentimes, there is a missing curly bracket in your function code:

```js
function charge() {
  if (sunny) {
    useSolarCells();
  } else {
    promptBikeRide();
}
```

Correct would be:

```js
function charge() {
  if (sunny) {
    useSolarCells();
  } else {
    promptBikeRide();
  }
}
```

 It can be more obscure when using IIFEs or other constructs that use
 a lot of different parenthesis and curly braces, for example.

```js
(function () {
  if (Math.random() < 0.01) {
    doSomething();
  }
)();
```

 Oftentimes, indenting differently or double checking indentation helps to spot these
 errors.

```js
(function () {
  if (Math.random() < 0.01) {
    doSomething();
  }
})();
```

See also
--------

* Functions guide


RangeError: argument is not a valid code point - JavaScript

RangeError: argument is not a valid code point
==============================================

 The JavaScript exception "Invalid code point" occurs when `NaN` values,
 negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111) are
 used with `String.fromCodePoint()`.

Message
-------
```

RangeError: Invalid code point -1 (V8-based)
RangeError: -1 is not a valid code point (Firefox)
RangeError: Arguments contain a value that is out of range of code points (Safari)
```

Error type
----------

`RangeError`What went wrong?
----------------

`String.fromCodePoint()` throws this error when passed `NaN`
 values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF
 (1114111).

 A code point is a value in the
 Unicode codespace; that is, the range of integers from `0` to
 `0x10FFFF`.

Examples
--------

### Invalid cases

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

### Valid cases

```js
String.fromCodePoint(42); // "\*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // 'Є' (U+0404)
String.fromCodePoint(0x2f804); // '你' (U+2F804)
String.fromCodePoint(194564); // '你'
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // '𝌆a𝌇'
```

See also
--------

* `String.fromCodePoint()`