RangeError: invalid array length - JavaScript

RangeError: invalid array length
================================

The JavaScript exception "Invalid array length" occurs when specifying an array length that is either negative, a floating number or exceeds the maximum supported by the platform (i.e. when creating an `Array` or `ArrayBuffer`, or when setting the `length` property).

 The maximum allowed array length depends on the platform, browser and browser version.
 For `Array` the maximum length is 232-1.
 For `ArrayBuffer` the maximum is 231-1 (2GiB-1) on 32-bit systems.
 From Firefox version 89 the maximum value of `ArrayBuffer` is 233 (8GiB) on 64-bit systems.

**Note:** `Array` and `ArrayBuffer` are independent data structures (the implementation of one does not affect the other).

Message
-------
```

RangeError: invalid array length (V8-based & Firefox)
RangeError: Array buffer allocation failed (V8-based)
RangeError: Array size is not a small enough positive integer. (Safari)
```

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

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

An invalid array length might appear in these situations:

* Creating an `Array` or `ArrayBuffer` with a negative length, or setting a negative value for the `length` property.
* Creating an `Array` or setting the `length` property greater than 232-1.
* Creating an `ArrayBuffer` that is bigger than 231-1 (2GiB-1) on a 32-bit system, or 233 (8GiB) on a 64-bit system.
* Creating an `Array` or setting the `length` property to a floating-point number.
* Before Firefox 89: Creating an `ArrayBuffer` that is bigger than 231-1 (2GiB-1).

 If you are creating an `Array`, using the constructor, you probably want to
 use the literal notation instead, as the first argument is interpreted as the length of
 the `Array`.

 Otherwise, you might want to clamp the length before setting the length property, or
 using it as argument of the constructor.

Examples
--------

### Invalid cases

```js
new Array(Math.pow(2, 40));
new Array(-1);
new ArrayBuffer(Math.pow(2, 32)); // 32-bit system
new ArrayBuffer(-1);

const a = [];
a.length = a.length - 1; // set the length property to -1

const b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // set the length property to 2^32
b.length = 2.5; // set the length property to a floating-point number

const c = new Array(2.5); // pass a floating-point number
```

### Valid cases

```js
[Math.pow(2, 40)]; // [ 1099511627776 ]
[-1]; // [ -1 ]
new ArrayBuffer(Math.pow(2, 31) - 1);
new ArrayBuffer(Math.pow(2, 33)); // 64-bit systems after Firefox 89
new ArrayBuffer(0);

const a = [];
a.length = Math.max(0, a.length - 1);

const b = new Array(Math.pow(2, 32) - 1);
b.length = Math.min(0xffffffff, b.length + 1);
// 0xffffffff is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)

b.length = 3;

const c = new Array(3);
```

See also
--------

* `Array`
* `length`
* `ArrayBuffer`


RangeError: x can't be converted to BigInt because it isn't an integer - JavaScript

RangeError: x can't be converted to BigInt because it isn't an integer
======================================================================

The JavaScript exception "x can't be converted to BigInt because it isn't an integer" occurs when the `BigInt()` function is used on a number that isn't an integer.

Message
-------
```

RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer (V8-based & Firefox)
RangeError: Not an integer (Safari)
```

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

`RangeError`.

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

When using the `BigInt()` function to convert a number to a BigInt, the number must be an integer (such that `Number.isInteger` returns true).

Examples
--------

### Invalid cases

```js
const a = BigInt(1.5);
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
const b = BigInt(NaN);
// RangeError: NaN cannot be converted to a BigInt because it is not an integer
```

### Valid cases

```js
const a = BigInt(1);
```

See also
--------

* `BigInt()` constructor
* `Number.isInteger()`


SyntaxError: continue must be inside loop - JavaScript

SyntaxError: continue must be inside loop
=========================================

The JavaScript exception "continue must be inside loop" occurs when a `continue` statement is not inside a loop statement.

Message
-------
```

SyntaxError: Illegal continue statement: no surrounding iteration statement (V8-based)
SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement (V8-based)
SyntaxError: continue must be inside loop (Firefox)
SyntaxError: 'continue' is only valid inside a loop statement. (Safari)
SyntaxError: Cannot continue to the label 'label' as it is not targeting a loop. (Safari)
```

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

`SyntaxError`.

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

`continue` statements can be used to continue a loop, and using them elsewhere is a syntax error. Alternatively, you can provide a label to the `continue` statement to continue any loop with that label — however, if the label does not reference a containing statement, another error SyntaxError: label not found will be thrown, and if the label references a statement that is not a loop, a syntax error is still thrown.

Examples
--------

### Using continue in callbacks

If you want to proceed with the next iteration in a `forEach()` loop, use `return` instead, or convert it to a `for...of` loop.

```js
array.forEach((value) => {
  if (value === 5) {
    continue; // SyntaxError: continue must be inside loop
  }
  // do something with value
});
```

```js
array.forEach((value) => {
  if (value === 5) {
    return;
  }
  // do something with value
});
```

```js
for (const value of array) {
  if (value === 5) {
    continue;
  }
  // do something with value
}
```

See also
--------

* `continue`


SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript

SyntaxError: "use strict" not allowed in function with non-simple parameters
============================================================================

 The JavaScript exception "`"use strict"` not allowed in function" occurs
 when a `"use strict"` directive is used at the top of a function with
 default parameters,
 rest parameters, or
 destructuring parameters.

Message
-------
```

SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based)
SyntaxError: "use strict" not allowed in function with default parameter (Firefox)
SyntaxError: "use strict" not allowed in function with rest parameter (Firefox)
SyntaxError: "use strict" not allowed in function with destructuring parameter (Firefox)
SyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)
```

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

`SyntaxError`.

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

 A `"use strict"` directive is written at the top of a function that has one
 of the following parameters:

* Default parameters
* Rest parameters
* Destructuring parameters

 A `"use strict"` directive is not allowed at the top of such functions per
 the ECMAScript specification.

Examples
--------

### Function statement

 In this case, the function `sum` has default parameters `a=1` and
 `b=2`:

```js
function sum(a = 1, b = 2) {
  // SyntaxError: "use strict" not allowed in function with default parameter
  "use strict";
  return a + b;
}
```

 If the function should be in strict mode, and the
 entire script or enclosing function is also okay to be in strict mode, you can move the
 `"use strict"` directive outside of the function:

```js
"use strict";
function sum(a = 1, b = 2) {
  return a + b;
}
```

### Function expression

A function expression can use yet another workaround:

```js
const sum = function sum([a, b]) {
  // SyntaxError: "use strict" not allowed in function with destructuring parameter
  "use strict";
  return a + b;
};
```

This can be converted to the following expression:

```js
const sum = (function () {
  "use strict";
  return function sum([a, b]) {
    return a + b;
  };
})();
```

### Arrow function

 If an arrow function needs to access the `this` variable, you can use the
 arrow function as the enclosing function:

```js
const callback = (...args) => {
  // SyntaxError: "use strict" not allowed in function with rest parameter
  "use strict";
  return this.run(args);
};
```

This can be converted to the following expression:

```js
const callback = (() => {
  "use strict";
  return (...args) => {
    return this.run(args);
  };
})();
```

See also
--------

* Strict mode
* function statement
* function expression
* Default parameters
* Rest parameters
* Destructuring parameters


TypeError: invalid 'instanceof' operand 'x' - JavaScript

TypeError: invalid 'instanceof' operand 'x'
===========================================

 The JavaScript exception "invalid 'instanceof' operand" occurs when the right-hand side
 operands of the `instanceof` operator
 isn't used with a constructor object, i.e. an object which has a `prototype` property and is callable.

Message
-------
```

TypeError: Right-hand side of 'instanceof' is not an object (V8-based)
TypeError: Right-hand side of 'instanceof' is not callable (V8-based)
TypeError: invalid 'instanceof' operand "x" (Firefox)
TypeError: ({}) is not a function (Firefox)
TypeError: Right hand side of instanceof is not an object (Safari)
TypeError: {} is not a function. (evaluating '"x" instanceof {}') (Safari)
```

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

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

 The `instanceof` operator expects
 the right-hand-side operands to be a constructor object,
 i.e. an object which has a `prototype` property and is callable. It can also be an object with a `Symbol.hasInstance` method.

Examples
--------

### instanceof vs. typeof

```js
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
42 instanceof 0; // TypeError: invalid 'instanceof' operand 0

function Foo() {}
const f = Foo(); // Foo() is called and returns undefined
const x = new Foo();

x instanceof f; // TypeError: invalid 'instanceof' operand f
x instanceof x; // TypeError: x is not a function
```

 To fix these errors, you will either need to replace
 the `instanceof` operator
 with the `typeof` operator,
 or to make sure you use the function name, instead of the result of its evaluation.

```js
typeof "test" === "string"; // true
typeof 42 === "number"; // true

function Foo() {}
const f = Foo; // Do not call Foo.
const x = new Foo();

x instanceof f; // true
x instanceof Foo; // true
```

See also
--------

* `instanceof`
* `typeof`


SyntaxError: redeclaration of formal parameter "x" - JavaScript

SyntaxError: redeclaration of formal parameter "x"
==================================================

 The JavaScript exception "redeclaration of formal parameter" occurs when the same
 variable name occurs as a function parameter and is then redeclared using a
 `let` assignment in a function body again.

Message
-------
```

SyntaxError: Identifier "x" has already been declared (V8-based)
SyntaxError: redeclaration of formal parameter "x" (Firefox)
SyntaxError: Cannot declare a let variable twice: 'x'. (Safari)
```

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

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

 The same variable name occurs as a function parameter and is then redeclared using a
 `let` assignment in a function body again. Redeclaring the
 same variable within the same function or block scope using `let` is not
 allowed in JavaScript.

Examples
--------

### Redeclared argument

In this case, the variable "arg" redeclares the argument.

```js
function f(arg) {
  let arg = "foo";
}

// SyntaxError: redeclaration of formal parameter "arg"
```

 If you want to change the value of "arg" in the function body, you can do so, but you
 do not need to declare the same variable again. In other words: you can omit the
 `let` keyword. If you want to create a new variable, you need to rename it as
 conflicts with the function parameter already.

```js
function f(arg) {
  arg = "foo";
}

function g(arg) {
  let bar = "foo";
}
```

See also
--------

* `let`
* `const`
* `var`
* Grammar and types guide


TypeError: property "x" is non-configurable and can't be deleted - JavaScript

TypeError: property "x" is non-configurable and can't be deleted
================================================================

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

Message
-------
```

TypeError: Cannot delete property 'x' of #<Object> (V8-based)
TypeError: property "x" is non-configurable and can't be deleted (Firefox)
TypeError: Unable to delete property. (Safari)
```

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

`TypeError` in strict mode only.

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

 It was attempted to delete 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.

 This error happens only in strict mode code. In
 non-strict code, the operation returns `false`.

Examples
--------

### Attempting to delete non-configurable properties

 Non-configurable 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 });
delete obj.score; // TypeError
```

```js
"use strict";
const obj = {};
Object.defineProperty(obj, "foo", { value: 2, configurable: false });
delete obj.foo; // TypeError
```

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

 There are also a few non-configurable properties built into JavaScript. Maybe you tried
 to delete a mathematical constant.

```js
"use strict";
delete Math.PI; // TypeError
```

See also
--------

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


TypeError: X.prototype.y called on incompatible type - JavaScript

TypeError: X.prototype.y called on incompatible type
====================================================

 The JavaScript exception "called on incompatible target (or object)" occurs when a
 function (on a given object), is called with a `this` not corresponding to
 the type expected by the function.

Message
-------
```

TypeError: Method Set.prototype.add called on incompatible receiver undefined (V8-based)
TypeError: Bind must be called on a function (V8-based)
TypeError: Function.prototype.toString called on incompatible object (Firefox)
TypeError: Function.prototype.bind called on incompatible target (Firefox)
TypeError: Type error (Safari)
TypeError: undefined is not an object (Safari)
```

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

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

 When this error is thrown, a function (on a given object), is called with a
 `this` not corresponding to the type expected by the function.

 This issue can arise when using the `Function.prototype.call()` or
 `Function.prototype.apply()` methods, and providing a `this`
 argument which does not have the expected type.

 This issue can also happen when providing a function that is stored as a property of an
 object as an argument to another function. In this case, the object that stores the
 function won't be the `this` target of that function when it is called by the
 other function. To work-around this issue, you will either need to provide a lambda
 which is making the call, or use the `Function.prototype.bind()` function to
 force the `this` argument to the expected object.

Examples
--------

### Invalid cases

```js
const mySet = new Set();
["bar", "baz"].forEach(mySet.add);
// mySet.add is a function, but "mySet" is not captured as this.

const myFun = function () {
  console.log(this);
};
["bar", "baz"].forEach(myFun.bind);
// myFun.bind is a function, but "myFun" is not captured as this.
```

### Valid cases

```js
const mySet = new Set();
["bar", "baz"].forEach(mySet.add.bind(mySet));
// This works due to binding "mySet" as this.

const myFun = function () {
  console.log(this);
};
["bar", "baz"].forEach((x) => myFun.bind(x));
// This works using the "bind" function. It creates a lambda forwarding the argument.
```

See also
--------

* `Function.prototype.call()`
* `Function.prototype.apply()`
* `Function.prototype.bind()`


SyntaxError: missing } after property list - JavaScript

SyntaxError: missing } after property list
==========================================

 The JavaScript exception "missing } after property list" occurs when there is a mistake
 in the object initializer syntax somewhere.
 Might be in fact a missing curly bracket, but could also be a missing comma.

Message
-------
```

SyntaxError: missing } after property list (Firefox)
SyntaxError: Unexpected identifier 'c'. Expected '}' to end an object literal. (Safari)
```

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

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

 There is a mistake in the object initializer
 syntax somewhere. Might be in fact a missing curly bracket, but could
 also be a missing comma, for example. 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 comma

Oftentimes, there is a missing comma in your object initializer code:

```js
const obj = {
  a: 1,
  b: { myProp: 2 }
  c: 3
};
```

Correct would be:

```js
const obj = {
  a: 1,
  b: { myProp: 2 },
  c: 3,
};
```

See also
--------

* Object initializer


SyntaxError: "x" is a reserved identifier - JavaScript

SyntaxError: "x" is a reserved identifier
=========================================

 The JavaScript exception "*variable* is a reserved identifier" occurs
 when reserved keywords are used as identifiers.

Message
-------
```

SyntaxError: Unexpected reserved word (V8-based)
SyntaxError: implements is a reserved identifier (Firefox)
SyntaxError: Cannot use the reserved word 'implements' as a variable name. (Safari)
```

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

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

Reserved keywords will throw in
 if they are used as identifiers. These are reserved in
 strict mode and sloppy mode:

* `enum`

The following are only reserved when they are found in strict mode code:

* `implements`
* `interface`
* `let`
* `package`
* `private`
* `protected`
* `public`
* `static`
Examples
--------

### Strict and non-strict reserved keywords

The `enum` identifier is generally reserved.

```js
const enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier
```

In strict mode code, more identifiers are reserved.

```js
"use strict";
const package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier
```

You'll need to rename these variables.

```js
const colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
const list = ["potatoes", "rice", "fries"];
```

### Update older browsers

 If you are using an older browser that does not yet implement
 `let` or
 `class`,
 for example, you should update to a more recent browser version that does support these
 new language features.

```js
"use strict";
class DocArchiver {}

// SyntaxError: class is a reserved identifier
// (throws in older browsers only, e.g. Firefox 44 and older)
```

See also
--------

* Lexical grammar


ReferenceError: "x" is not defined - JavaScript

ReferenceError: "x" is not defined
==================================

 The JavaScript exception "*variable* is not defined" occurs when there is a
 non-existent variable referenced somewhere.

Message
-------
```

ReferenceError: "x" is not defined (V8-based & Firefox)
ReferenceError: Can't find variable: x (Safari)
```

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

`ReferenceError`.

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

 There is a non-existent variable referenced somewhere. This variable needs to be
 declared, or you need to make sure it is available in your current script or scope.

**Note:** When loading a library (such as jQuery), make sure it is
 loaded before you access library variables, such as "$". Put the
 `<script>` element that loads the library before your code that uses
 it.

Examples
--------

### Variable not declared

```js
foo.substring(1); // ReferenceError: foo is not defined
```

 The "foo" variable isn't defined anywhere. It needs to be some string, so that the
 `String.prototype.substring()` method will work.

```js
const foo = "bar";
foo.substring(1); // "ar"
```

### Wrong scope

 A variable needs to be available in the current context of execution. Variables defined
 inside a function cannot be
 accessed from anywhere outside the function, because the variable is defined only in the
 scope of the function

```js
function numbers() {
  const num1 = 2;
  const num2 = 3;
  return num1 + num2;
}

console.log(num1); // ReferenceError num1 is not defined.
```

 However, a function can access all variables and functions defined inside the scope in
 which it is defined. In other words, a function defined in the global scope can access
 all variables defined in the global scope.

```js
const num1 = 2;
const num2 = 3;

function numbers() {
  return num1 + num2;
}

console.log(numbers()); // 5
```

See also
--------

* Scope
* Declaring variables in the JavaScript Guide
* Function scope in the JavaScript Guide


TypeError: can't assign to property "x" on "y": not an object - JavaScript

TypeError: can't assign to property "x" on "y": not an object
=============================================================

 The JavaScript strict mode exception "can't assign to property" occurs when attempting
 to create a property on primitive value
 such as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

Message
-------
```

TypeError: Cannot create property 'x' on number '1' (V8-based)
TypeError: can't assign to property "x" on 1: not an object (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```

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

`TypeError`.

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

 In strict mode, a `TypeError` is raised when attempting to
 create a property on primitive value such
 as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

 The problem might be that an unexpected value is flowing at an unexpected place, or
 that an object variant of a `String` or a `Number` is expected.

Examples
--------

### Invalid cases

```js
"use strict";

const foo = "my string";
// The following line does nothing if not in strict mode.
foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
```

### Fixing the issue

Either fix the code to prevent the primitive from being used in such places, or fix the issue by creating the object equivalent `Object`.

```js
"use strict";

const foo = new String("my string");
foo.bar = {};
```

See also
--------

* Strict mode
* primitive


Warning: unreachable code after return statement - JavaScript

Warning: unreachable code after return statement
================================================

 The JavaScript warning "unreachable code after return statement" occurs when using an
 expression after a `return` statement, or when using a
 semicolon-less return statement but including an expression directly after.

Message
-------
```

Warning: unreachable code after return statement (Firefox)
```

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

Warning

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

Unreachable code after a return statement might occur in these situations:

* When using an expression after a `return`
 statement, or
* when using a semicolon-less return statement but including an expression directly
 after.

 When an expression exists after a valid `return` statement, a warning is
 given to indicate that the code after the `return` statement is unreachable,
 meaning it can never be run.

 Why should I have semicolons after `return` statements? In the case of
 semicolon-less `return` statements, it can be unclear whether the developer
 intended to return the statement on the following line, or to stop execution and return.
 The warning indicates that there is ambiguity in the way the `return`
 statement is written.

Warnings will not be shown for semicolon-less returns if these statements follow it:

* `throw`
* `break`
* `var`
* `function`
Examples
--------

### Invalid cases

```js
function f() {
  let x = 3;
  x += 4;
  return x;   // return exits the function immediately
  x -= 3;     // so this line will never run; it is unreachable
}

function g() {
  return     // this is treated like `return;`
    3 + 4;   // so the function returns, and this line is never reached
}
```

### Valid cases

```js
function f() {
  let x = 3;
  x += 4;
  x -= 3;
  return x; // OK: return after all other statements
}

function g() {
  return 3 + 4 // OK: semicolon-less return with expression on the same line
}
```

See also
--------

* Automatic semicolon insertion


SyntaxError: invalid BigInt syntax - JavaScript

SyntaxError: invalid BigInt syntax
==================================

The JavaScript exception "invalid BigInt syntax" occurs when a string value is being coerced to a `BigInt` but it failed to be parsed as an integer.

Message
-------
```

SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)
```

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

`SyntaxError`.

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

When using the `BigInt()` function to convert a string to a BigInt, the string will be parsed in the same way as source code, and the resulting value must be an integer value.

Examples
--------

### Invalid cases

```js
const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");
// SyntaxError: invalid BigInt syntax
```

### Valid cases

```js
const a = BigInt("1");
const b = BigInt(" 1 ");
const c = BigInt.asIntN(4, "8");
```

See also
--------

* `BigInt`


SyntaxError: getter and setter for private name #x should either be both static or non-static - JavaScript

SyntaxError: getter and setter for private name #x should either be both static or non-static
=============================================================================================

The JavaScript exception "mismatched placement" occurs when a private getter and setter are mismatched in whether or not they are `static`.

Message
-------
```

SyntaxError: Identifier '#x' has already been declared (V8-based)
SyntaxError: getter and setter for private name #x should either be both static or non-static (Firefox)
SyntaxError: Cannot declare a private non-static getter if there is a static private setter with used name. (Safari)
```

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

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

Private getters and setters for the same name must either be both `static`, or both non-static. This limitation does not exist for public methods.

Examples
--------

### Mismatched placement

```js
class Test {
  static set #foo(\_) {}
  get #foo() {}
}

// SyntaxError: getter and setter for private name #foo should either be both static or non-static
```

Since `foo` is private, the methods must be either both `static`:

```js
class Test {
  static set #foo(\_) {}
  static get #foo() {}
}
```

or non-static:

```js
class Test {
  set #foo(\_) {}
  get #foo() {}
}
```

See also
--------

* `get`
* `set`
* `static`
* Private properties


RangeError: radix must be an integer - JavaScript

RangeError: radix must be an integer
====================================

 The JavaScript exception "radix must be an integer at least 2 and no greater than 36"
 occurs when the optional `radix` parameter of the
 `Number.prototype.toString()` or
 the `BigInt.prototype.toString()` method was specified and is not between 2
 and 36.

Message
-------
```

RangeError: toString() radix argument must be between 2 and 36 (V8-based & Safari)
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)
```

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

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

 The optional `radix` parameter of the
 `Number.prototype.toString()` or
 the `BigInt.prototype.toString()` method was specified. Its value must be an
 integer (a number) between 2 and 36, specifying the base of the number system to be used
 for representing numeric values. For example, the decimal (base 10) number 169 is
 represented in hexadecimal (base 16) as A9.

 Why is this parameter's value limited to 36? A radix that is larger than 10 uses
 alphabetical characters as digits; therefore, the radix can't be larger than 36, since
 the Latin alphabet (used by English and many other languages) only has 26 characters.

The most common radixes:

* 2 for binary numbers,
* 8 for octal numbers,
* 10 for decimal numbers,
* 16 for hexadecimal numbers.
Examples
--------

### Invalid cases

```js
(42).toString(0);
(42).toString(1);
(42).toString(37);
(42).toString(150);
// You cannot use a string like this for formatting:
(12071989).toString("MM-dd-yyyy");
```

### Valid cases

```js
(42).toString(2); // "101010" (binary)
(13).toString(8); // "15" (octal)
(0x42).toString(10); // "66" (decimal)
(100000).toString(16); // "186a0" (hexadecimal)
```

See also
--------

* `Number.prototype.toString()`
* `BigInt.prototype.toString()`


SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript

SyntaxError: test for equality (==) mistyped as assignment (=)?
===============================================================

 The JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when
 there was an assignment (`=`) when you would normally expect a test for
 equality (`==`).

Message
-------
```

Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
```

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

 (Firefox only) `SyntaxError` warning which is reported only if
 `javascript.options.strict` preference is set to `true`.

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

 There was an assignment (`=`) when you would normally expect a test for
 equality (`==`). To help debugging, JavaScript (with strict warnings enabled)
 warns about this pattern.

Examples
--------

### Assignment within conditional expressions

 It is advisable to not use simple assignments in a conditional expression (such as
 `if...else`),
 because the assignment can be confused with equality when glancing over the code. For
 example, do not use the following code:

```js
if (x = y) {
  // do the right thing
}
```

 If you need to use an assignment in a conditional expression, a common practice is to
 put additional parentheses around the assignment. For example:

```js
if ((x = y)) {
  // do the right thing
}
```

 Otherwise, you probably meant to use a comparison operator (e.g. `==` or
 `===`):

```js
if (x === y) {
  // do the right thing
}
```

See also
--------

* `if...else`
* Equality operators


SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript

SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
=============================================================================

 The JavaScript strict mode-only exception "0-prefixed octal literals and octal escape sequences are
 deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal
 literals and octal escape sequences are used.

Message
-------
```

SyntaxError: Octal literals are not allowed in strict mode. (V8-based)
SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead (Firefox)
SyntaxError: Decimal integer literals with a leading zero are forbidden in strict mode (Safari)

SyntaxError: Octal escape sequences are not allowed in strict mode. (V8-based)
SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code (Firefox)
SyntaxError: The only valid numeric escape in strict mode is '\0' (Safari)
```

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

`SyntaxError` in strict mode only.

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

 Octal literals and octal escape sequences are deprecated and will throw a
 `SyntaxError` in strict mode. The
 standardized syntax uses a leading zero followed by a lowercase or uppercase Latin
 letter "O" (`0o` or `0O`).

Examples
--------

### "0"-prefixed octal literals

```js
"use strict";

03;

// SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead
```

### Octal escape sequences

```js
"use strict";

"\251";

// SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
```

### Valid octal numbers

Use a leading zero followed by the letter "o" or "O":

```js
0o3;
```

For octal escape sequences, you can use hexadecimal escape sequences instead:

```js
"\xA9";
```

See also
--------

* Lexical grammar


TypeError: Reduce of empty array with no initial value - JavaScript

TypeError: Reduce of empty array with no initial value
======================================================

 The JavaScript exception "reduce of empty array with no initial value" occurs when a
 reduce function is used.

Message
-------
```

TypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)
```

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

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

In JavaScript, there are several reduce functions:

* `Array.prototype.reduce()`, `Array.prototype.reduceRight()`
 and
* `TypedArray.prototype.reduce()`,
 `TypedArray.prototype.reduceRight()`).

 These functions optionally take an `initialValue` (which will be used as the
 first argument to the first call of the `callback`). However, if no initial
 value is provided, it will use the first element of the `Array` or
 `TypedArray` as the initial value. This error is raised when an empty array
 is provided because no initial value can be returned in that case.

Examples
--------

### Invalid cases

 This problem appears frequently when combined with a filter
 (`Array.prototype.filter()`, `TypedArray.prototype.filter()`)
 which will remove all elements of the list. Thus leaving none to be used as the initial
 value.

```js
const ints = [0, -1, -2, -3, -4, -5];
ints
  .filter((x) => x > 0) // removes all elements
  .reduce((x, y) => x + y); // no more elements to use for the initial value.
```

 Similarly, the same issue can happen if there is a typo in a selector, or an unexpected
 number of elements in a list:

```js
const names = document.getElementsByClassName("names");
const name_list = Array.prototype.reduce.call(
  names,
  (acc, name) => acc + ", " + name,
);
```

### Valid cases

These problems can be solved in two different ways.

 One way is to actually provide an `initialValue` as the neutral element of
 the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for
 a concatenation.

```js
const ints = [0, -1, -2, -3, -4, -5];
ints
  .filter((x) => x > 0) // removes all elements
  .reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition
```

 Another way would be to handle the empty case, either before calling
 `reduce`, or in the callback after adding an unexpected dummy initial value.

```js
const names = document.getElementsByClassName("names");

let nameList1 = "";
if (names.length >= 1) {
  nameList1 = Array.prototype.reduce.call(
    names,
    (acc, name) => `${acc}, ${name}`,
  );
}
// nameList1 === "" when names is empty.

const nameList2 = Array.prototype.reduce.call(
  names,
  (acc, name) => {
    if (acc === "")
      // initial value
      return name;
    return `${acc}, ${name}`;
  },
  "",
);
// nameList2 === "" when names is empty.
```

See also
--------

* `Array.prototype.reduce()`
* `Array.prototype.reduceRight()`
* `TypedArray.prototype.reduce()`
* `TypedArray.prototype.reduceRight()`
* `Array`
* `TypedArray`
* `Array.prototype.filter()`
* `TypedArray.prototype.filter()`


SyntaxError: for-in loop head declarations may not have initializers - JavaScript

SyntaxError: for-in loop head declarations may not have initializers
====================================================================

 The JavaScript strict mode-only exception
 "for-in loop head declarations may not have initializers"
 occurs when the head of a for...in contains
 an initializer expression, such as `for (var i = 0 in obj)`. This is not
 allowed in for-in loops in strict mode. In addition, lexical declarations with initializers like `for (const i = 0 in obj)` are not allowed outside strict mode either.

Message
-------
```

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

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

`SyntaxError`.

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

 The head of a for...in loop contains an initializer expression.
 That is, a variable is declared and assigned a value `for (var i = 0 in obj)`.
 In non-strict mode, this head declaration is silently ignored and behaves like `for (var i in obj)`.
 In strict mode, however, a `SyntaxError` is thrown. In addition, lexical declarations with initializers like `for (const i = 0 in obj)` are not allowed outside strict mode either, and will always produce a `SyntaxError`.

Examples
--------

This example throws a `SyntaxError`:

```js
const obj = { a: 1, b: 2, c: 3 };

for (const i = 0 in obj) {
  console.log(obj[i]);
}

// SyntaxError: for-in loop head declarations may not have initializers
```

### Valid for-in loop

You can remove the initializer (`i = 0`) in the head of the for-in loop.

```js
const obj = { a: 1, b: 2, c: 3 };

for (const i in obj) {
  console.log(obj[i]);
}
```

### Array iteration

 The for...in loop shouldn't be used for Array iteration.
 Did you intend to use a `for` loop
 instead of a `for-in` loop to iterate an `Array`? The
 `for` loop allows you to set an initializer then as well:

```js
const arr = ["a", "b", "c"];

for (let i = 2; i < arr.length; i++) {
  console.log(arr[i]);
}

// "c"
```

See also
--------

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


SyntaxError: function statement requires a name - JavaScript

SyntaxError: function statement requires a name
===============================================

 The JavaScript exception "function statement requires a name" occurs
 when there is a function statement
 in the code that requires a name.

Message
-------
```

SyntaxError: Function statements require a function name (V8-based)
SyntaxError: function statement requires a name (Firefox)
SyntaxError: Function statements must have a name. (Safari)
```

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

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

 There is a function statement in the code that requires a name.
 You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all.

Examples
--------

### Statements vs. expressions

 A *function statement* (or *function declaration*) requires a name.
 This won't work:

```js
function () {
  return "Hello world";
}
// SyntaxError: function statement requires a name
```

You can use a function expression (assignment) instead:

```js
const greet = function () {
  return "Hello world";
};
```

If your function is intended to be an IIFE (Immediately Invoked Function Expression, which is a function that runs as soon as it is defined) you will need to add a few more braces:

```js
(function () {
  // …
})();
```

### Labeled functions

Labels are an entirely different feature from function names. You can't use a label as a function name.

```js
function Greeter() {
  german: function () {
    return "Moin";
  }
}
// SyntaxError: function statement requires a name
```

In addition, labeled function declarations themselves are a deprecated feature. Use regular function declarations instead.

```js
function Greeter() {
  function german() {
    return "Moin";
  }
}
```

### Object methods

 If you intended to create a method of an object, you will need to create an object.
 The following syntax without a name after the `function` keyword is valid then.

```js
const greeter = {
  german: function () {
    return "Moin";
  },
};
```

You can also use the method syntax.

```js
const greeter = {
  german() {
    return "Moin";
  },
};
```

### Callback syntax

 Also, check your syntax when using callbacks.
 Braces and commas can quickly get confusing.

```js
promise.then(
  function () {
    console.log("success");
  });
  function () {
    console.log("error");
}
// SyntaxError: function statement requires a name
```

Correct would be:

```js
promise.then(
  function () {
    console.log("success");
  },
  function () {
    console.log("error");
  },
);
```

See also
--------

* Functions guide
* `function`
* `function` expression
* IIFE
* Labeled statement


SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' - JavaScript

SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '\*\*'
==========================================================================================

The JavaScript exception "unparenthesized unary expression can't appear on the left-hand side of '\*\*'" occurs when a unary operator (one of `typeof`, `void`, `delete`, `await`, `!`, `~`, `+`, `-`) is used on the left operand of the exponentiation operator without parentheses.

Message
-------
```

SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence (V8-based)
SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' (Firefox)
SyntaxError: Unexpected token '**'. Ambiguous unary expression in the left hand side of the exponentiation expression; parentheses must be used to disambiguate the expression. (Safari)
```

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

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

You likely wrote something like this:

```js
-a \*\* b
```

Whether it should be evaluated as `(-a) ** b` or `-(a ** b)` is ambiguous. In mathematics, -x2 means `-(x ** 2)` — and that's how many languages, including Python, Haskell, and PHP, handle it. But making the unary minus operator take precedence over `**` breaks symmetry with `a ** -b`, which is unambiguously `a ** (-b)`. Therefore, the language forbids this syntax and requires you to parenthesize either side to resolve the ambiguity.

```js
(-a) \*\* b
-(a \*\* b)
```

Other unary operators cannot be the left-hand side of exponentiation either.

```js
await a \*\* b
!a \*\* b
+a \*\* b
~a \*\* b
```

Examples
--------

When writing complex math expressions involving exponentiation, you may write something like this:

```js
function taylorSin(x) {
  return (n) => (-1 \*\* n \* x \*\* (2 \* n + 1)) / factorial(2 \* n + 1);
  // SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '\*\*'
}
```

However, the `-1 ** n` part is illegal in JavaScript. Instead, parenthesize the left operand:

```js
function taylorSin(x) {
  return (n) => ((-1) \*\* n \* x \*\* (2 \* n + 1)) / factorial(2 \* n + 1);
}
```

This also makes the code's intent much clearer to other readers.

See also
--------

* Exponentiation (`**`)
* Operator precedence
* Original discussion of exponentiation operator precedence on esdiscuss.org


TypeError: "x" is (not) "y" - JavaScript

TypeError: "x" is (not) "y"
===========================

 The JavaScript exception "*x* is (not) *y*" occurs when there was an
 unexpected type. Oftentimes, unexpected `undefined` or `null`
 values.

Message
-------
```

TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: "x" is undefined (Firefox)
TypeError: "undefined" is not an object (Firefox)
TypeError: undefined is not an object (evaluating 'obj.x') (Safari)

TypeError: "x" is not a symbol (V8-based & Firefox)
TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
```

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

`TypeError`.

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

 There was an unexpected type. This occurs oftentimes with `undefined` or
 `null` values.

 Also, certain methods, such as `Object.create()` or
 `Symbol.keyFor()`, require a specific type, that must be provided.

Examples
--------

### Invalid cases

You cannot invoke a method on an `undefined` or `null` variable.

```js
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined

const foo2 = null;
foo2.substring(1); // TypeError: foo is null
```

Certain methods might require a specific type.

```js
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol

const foo2 = "bar";
Object.create(foo2); // TypeError: "foo" is not an object or null
```

### Fixing the issue

To fix null pointer to `undefined` or `null` values, you can test if the value is `undefined` or `null` first.

```js
if (foo !== undefined && foo !== null) {
  // Now we know that foo is defined, we are good to go.
}
```

Or, if you are confident that `foo` will not be another falsy value like `""` or `0`, or if filtering those cases out is not an issue, you can simply test for its truthiness.

```js
if (foo) {
  // Now we know that foo is truthy, it will necessarily not be null/undefined.
}
```

See also
--------

* `undefined`
* `null`


TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript

TypeError: cannot use 'in' operator to search for 'x' in 'y'
============================================================

 The JavaScript exception "right-hand side of 'in' should be an object" occurs when the
 `in` operator
 was used to search in strings, or in numbers, or other primitive types. It can only be
 used to check if a property is in an object.

Message
-------
```

TypeError: Cannot use 'in' operator to search for 'x' in 'y' (V8-based & Firefox)
TypeError: right-hand side of 'in' should be an object, got null (Firefox)
TypeError: "y" is not an Object. (evaluating '"x" in "y"') (Safari)
```

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

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

 The `in` operator can only be used
 to check if a property is in an object.
 You can't search in strings, or in numbers, or other primitive types.

Examples
--------

### Searching in strings

 Unlike in other programming languages (e.g. Python), you can't search in strings using
 the `in` operator.

```js
"Hello" in "Hello World";
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'
```

Instead you will need to use `String.prototype.includes()`, for example.

```js
"Hello World".includes("Hello");
// true
```

### The operand can't be null or undefined

 Make sure the object you are inspecting isn't actually `null` or
 `undefined`.

```js
const foo = null;
"bar" in foo;
// TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome)
// TypeError: right-hand side of 'in' should be an object, got null (Firefox)
```

The `in` operator always expects an object.

```js
const foo = { baz: "bar" };
"bar" in foo; // false

"PI" in Math; // true
"pi" in Math; // false
```

### Searching in arrays

 Be careful when using the `in` operator to search in `Array`
 objects. The `in` operator checks the index number, not the value at that
 index.

```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
3 in trees; // true
"oak" in trees; // false
```

See also
--------

* `in`


Error: Permission denied to access property "x" - JavaScript

Error: Permission denied to access property "x"
===============================================

 The JavaScript exception "Permission denied to access property" occurs when there was
 an attempt to access an object for which you have no permission.

Message
-------
```

DOMException: Blocked a frame with origin "x" from accessing a cross-origin frame. (Chromium-based)
DOMException: Permission denied to access property "x" on cross-origin object (Firefox)
SecurityError: Blocked a frame with origin "x" from accessing a cross-origin frame. Protocols, domains, and ports must match. (Safari)
```

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

`DOMException`.

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

 There was attempt to access an object for which you have no permission. This is likely
 an `<iframe>` element loaded from a different domain for which you
 violated the same-origin policy.

Examples
--------

### No permission to access document

```html
<!doctype html>
<html lang="en-US">
  <head>
    <iframe
 id="myframe"
 src="http://www1.w3c-test.org/common/blank.html"></iframe>
    <script>
 onload = function () {
 console.log(frames[0].document);
 // Error: Permission denied to access property "document"
 };
 </script>
  </head>
  <body></body>
</html>
```

See also
--------

* `<iframe>`
* Same-origin policy


SyntaxError: missing : after property id - JavaScript

SyntaxError: missing : after property id
========================================

 The JavaScript exception "missing : after property id" occurs when objects are created
 using the object initializer syntax.
 A colon (`:`) separates keys and values for the
 object's properties. Somehow, this colon is missing or misplaced.

Message
-------
```

SyntaxError: Invalid shorthand property initializer (V8-based)
SyntaxError: missing : after property id (Firefox)
SyntaxError: Unexpected token '='. Expected a ':' following the property name 'x'. (Safari)
SyntaxError: Unexpected token '+'. Expected an identifier as property name. (Safari)
```

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

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

 When creating objects with the object initializer syntax,
 a colon (`:`) separates keys and values for the object's properties.

```js
const obj = { propertyKey: "value" };
```

Examples
--------

### Colons vs. equal signs

 This code fails, as the equal sign can't be used this way in this object initializer
 syntax.

```js
const obj = { propertyKey = "value" };
// SyntaxError: missing : after property id
```

 Correct would be to use a colon, or to use square brackets to assign a new property
 after the object has been created already.

```js
const obj = { propertyKey: "value" };
```

Or alternatively:

```js
const obj = {};
obj.propertyKey = "value";
```

### Computed properties

 If you create a property key from an expression, you need to use square brackets.
 Otherwise the property name can't be computed:

```js
const obj = { "b"+"ar": "foo" };
// SyntaxError: missing : after property id
```

Put the expression in square brackets `[]`:

```js
const obj = { ["b" + "ar"]: "foo" };
```

See also
--------

* Object initializer


SyntaxError: Unexpected token - JavaScript

SyntaxError: Unexpected token
=============================

 The JavaScript exceptions "unexpected token" occur when a specific language construct
 was expected, but something else was provided. This might be a simple typo.

Message
-------
```

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"
```

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

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

 A specific language construct was expected, but something else was provided. This might
 be a simple typo.

Examples
--------

### Expression expected

For example, when chaining expressions, trailing commas are not allowed.

```js
for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'
```

Correct would be omitting the comma or adding another expression:

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

### Not enough parentheses

Sometimes, you leave out parentheses around `if` statements:

```js
function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { // Not enough parenthese here!
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'
```

 The parentheses may look correct at first, but note how the `||` is outside the
 parentheses. Correct would be putting parentheses around the `||`:

```js
function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(
      `Number ${n} is more than ${upperBound} or less than ${lowerBound}`,
    );
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}
```

See also
--------

* `SyntaxError`


TypeError: setting getter-only property "x" - JavaScript

TypeError: setting getter-only property "x"
===========================================

 The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt
 to set a new value to a property for which only a getter is specified.

Message
-------
```

TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
```

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

`TypeError` in strict mode only.

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

 There is an attempt to set a new value to a property for which only a getter is specified.
 While this will be silently ignored in non-strict mode, it will throw a
 `TypeError` in strict mode.

Examples
--------

### Property with no setter

 The example below shows how to set a getter for a property.
 It doesn't specify a setter, so a
 `TypeError` will be thrown upon trying to set the `temperature`
 property to `30`. For more details see also the
 `Object.defineProperty()` page.

```js
"use strict";

function Archiver() {
  const temperature = null;
  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
  });
}

const arc = new Archiver();
arc.temperature; // 'get!'

arc.temperature = 30;
// TypeError: setting getter-only property "temperature"
```

 To fix this error, you will either need to remove line 16, where there is an attempt to
 set the temperature property, or you will need to implement a setter for it, for
 example like this:

```js
"use strict";

function Archiver() {
  let temperature = null;
  const archive = [];

  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
    set(value) {
      temperature = value;
      archive.push({ val: temperature });
    },
  });

  this.getArchive = function () {
    return archive;
  };
}

const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
```

See also
--------

* `Object.defineProperty()`
* `Object.defineProperties()`


SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript

SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
================================================================================

The JavaScript strict mode-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the `delete` operator.

Message
-------
```

SyntaxError: Delete of an unqualified identifier in strict mode. (V8-based)
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)
SyntaxError: Cannot delete unqualified property 'a' in strict mode. (Safari)
```

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

`SyntaxError` in strict mode only.

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

Normal variables in JavaScript can't be deleted using the `delete` operator. In strict mode, an attempt to delete a variable will throw an error and is not allowed.

The `delete` operator can only delete properties on an object. Object properties are "qualified" if they are configurable.

Unlike what common belief suggests, the `delete` operator has **nothing** to do with directly freeing memory. Memory management is done indirectly via breaking references, see the memory management page and the `delete` operator page for more details.

This error only happens in strict mode code. In non-strict code, the operation just returns `false`.

Examples
--------

### Freeing the contents of a variable

Attempting to delete a plain variable throws an error in strict mode:

```js
"use strict";

var x;

// …

delete x;

// SyntaxError: applying the 'delete' operator to an unqualified name
// is deprecated
```

To free the contents of a variable, you can set it to `null`:

```js
"use strict";

var x;

// …

x = null;

// x can be garbage collected
```

See also
--------

* `delete`
* Memory management
* TypeError: property "x" is non-configurable and can't be deleted


SyntaxError: unterminated string literal - JavaScript

SyntaxError: unterminated string literal
========================================

 The JavaScript error "unterminated string literal" occurs when there is an unterminated
 string literal somewhere. String literals must be enclosed by single
 (`'`) or double (`"`) quotes.

Message
-------
```

SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)
```

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

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

 There is an unterminated
 string literal somewhere. String literals must be
 enclosed by single (`'`) or double (`"`) quotes. JavaScript makes
 no distinction between single-quoted strings and double-quoted strings.
 Escape sequences work
 in strings created with either single or double quotes.
 To fix this error, check if:

* you have opening and closing quotes (single or double) for your string literal,
* you have escaped your string literal correctly,
* your string literal isn't split across multiple lines.
Examples
--------

### Multiple lines

You can't split a string across multiple lines like this in JavaScript:

```js
const longString = "This is a very long string which needs
                    to wrap across multiple lines because
                    otherwise my code is unreadable.";
// SyntaxError: unterminated string literal
```

 Instead, use the + operator,
 a backslash, or template literals.
 The `+` operator variant looks like this:

```js
const longString =
  "This is a very long string which needs " +
  "to wrap across multiple lines because " +
  "otherwise my code is unreadable.";
```

 Or you can use the backslash character ("\") at the end of each line to indicate that
 the string will continue on the next line. Make sure there is no space or any other
 character after the backslash (except for a line break), or as an indent; otherwise it
 will not work. That form looks like this:

```js
const longString =
  "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
```

Another possibility is to use template literals.

```js
const longString = `This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.`;
```

See also
--------

* string literal
* Template literals


ReferenceError: reference to undefined property "x" - JavaScript

ReferenceError: reference to undefined property "x"
===================================================

 The JavaScript warning "reference to undefined property" occurs when a script attempted
 to access an object property which doesn't exist.

Message
-------
```

ReferenceError: reference to undefined property "x" (Firefox)
```

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

 (Firefox only) `ReferenceError` warning which is reported only if
 `javascript.options.strict` preference is set to `true`.

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

 The script attempted to access an object property which doesn't exist. There are two
 ways to access properties; see the property accessors reference page to learn more about them.

Examples
--------

### Invalid cases

 In this case, the property `bar` is an undefined property, so a
 `ReferenceError` will occur.

```js
const foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"
```

### Valid cases

 To avoid the error, you need to either add a definition for `bar` to the
 object or check for the existence of the `bar` property before trying to
 access it; ways to do that include using the `in` operator,
 or the `Object.hasOwn()` method, like this:

```js
const foo = {};

// Define the bar property

foo.bar = "moon";
console.log(foo.bar); // "moon"

// Test to be sure bar exists before accessing it

if (Object.hasOwn(foo, "bar")) {
  console.log(foo.bar);
}
```

See also
--------

* Property accessors


TypeError: "x" has no properties - JavaScript

TypeError: "x" has no properties
================================

 The JavaScript exception "null (or undefined) has no properties" occurs when you
 attempt to access properties of `null` and `undefined`. They
 don't have any.

Message
-------
```

TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: null has no properties (Firefox)
TypeError: undefined has no properties (Firefox)
TypeError: undefined is not an object (evaluating 'undefined.x') (Safari)
```

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

`TypeError`.

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

 Both `null` and `undefined`, have no properties you could
 access.

Examples
--------

### null and undefined have no properties

```js
null.foo;
// TypeError: null has no properties

undefined.bar;
// TypeError: undefined has no properties
```

See also
--------

* `null`
* `undefined`


SyntaxError: invalid assignment left-hand side - JavaScript

SyntaxError: invalid assignment left-hand side
==============================================

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. It may be triggered when a single `=` sign was used instead of `==` or `===`.

Message
-------
```

SyntaxError: Invalid left-hand side in assignment (V8-based)
SyntaxError: invalid assignment left-hand side (Firefox)
SyntaxError: Left side of assignment is not a reference. (Safari)
```

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

`SyntaxError` or `ReferenceError`, depending on the syntax.

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

There was an unexpected assignment somewhere. This might be due to a mismatch of an assignment operator and an equality operator, for example. While a single `=` sign assigns a value to a variable, the `==` or `===` operators compare a value.

Examples
--------

### Typical invalid assignments

```js
if (Math.PI + 1 = 3 || Math.PI + 1 = 4) {
  console.log("no way!");
}
// SyntaxError: invalid assignment left-hand side

const str = "Hello, "
+= "is it me "
+= "you're looking for?";
// SyntaxError: invalid assignment left-hand side
```

In the `if` statement, you want to use an equality operator (`===`), and for the string concatenation, the plus (`+`) operator is needed.

```js
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {
  console.log("no way!");
}

const str = "Hello, "
  + "from the "
  + "other side!";
```

### Assignments producing ReferenceErrors

Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a *value* instead of a *reference*, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed.

```js
function foo() {
  return { a: 1 };
}
foo() = 1; // ReferenceError: invalid assignment left-hand side
```

Function calls, `new` calls, `super()`, and `this` are all values instead of references. If you want to use them on the left hand side, the assignment target needs to be a property of their produced values instead.

```js
function foo() {
  return { a: 1 };
}
foo().a = 1;
```

**Note:** In Firefox and Safari, the first example produces a `ReferenceError` in non-strict mode, and a `SyntaxError` in strict mode. Chrome throws a runtime `ReferenceError` for both strict and non-strict modes.

### Using optional chaining as assignment target

Optional chaining is not a valid target of assignment.

```js
obj?.foo = 1; // SyntaxError: invalid assignment left-hand side
```

Instead, you have to first guard the nullish case.

```js
if (obj) {
  obj.foo = 1;
}
```

See also
--------

* Assignment operators
* Equality operators


SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript

SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
===================================================================================

The JavaScript warning "Using `//@` to indicate sourceURL pragmas is deprecated. Use `//#` instead" occurs when there is a deprecated source map syntax in a JavaScript source.

Message
-------
```

Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead

Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
```

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

A warning that a `SyntaxError` occurred. JavaScript execution won't be halted.

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

There is a deprecated source map syntax in a JavaScript source.

JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files.

The source map specification changed the syntax due to a conflict with IE whenever it was found in the page after `//@cc_on` was interpreted to turn on conditional compilation in the IE JScript engine. The conditional compilation comment in IE is a little known feature, but it broke source maps with jQuery and other libraries.

Examples
--------

### Deprecated syntax

Syntax with the "@" sign is deprecated.

```js
//@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```

### Standard syntax

Use the "#" sign instead.

```js
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```

Or, alternatively, you can set a `SourceMap` header to your JavaScript file to avoid having a comment at all:

```http
SourceMap: /path/to/file.js.map
```

See also
--------

* Use a source map in the Firefox source docs
* Introduction to JavaScript source maps on developer.chrome.com (2012)
* `SourceMap`


RangeError: BigInt division by zero - JavaScript

RangeError: BigInt division by zero
===================================

The JavaScript exception "BigInt division by zero" occurs when a `BigInt` is divided by `0n`.

Message
-------
```

RangeError: Division by zero (V8-based)
RangeError: BigInt division by zero (Firefox)
RangeError: 0 is an invalid divisor value. (Safari)
```

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

`RangeError`.

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

The divisor of a division or remainder operator is `0n`. In `Number` arithmetic, this produces `Infinity`, but there's no "infinity value" in BigInts, so an error is issued. Check if the divisor is `0n` before doing the division.

Examples
--------

### Division by 0n

```js
const a = 1n;
const b = 0n;
const quotient = a / b;
// RangeError: BigInt division by zero
```

Instead, check if the divisor is `0n` first, and either issue an error with a better message, or fallback to a different value, like `Infinity` or `undefined`.

```js
const a = 1n;
const b = 0n;
const quotient = b === 0n ? undefined : a / b;
```

See also
--------

* `BigInt`
* Division (`/`)
* Remainder (`%`)


RangeError: repeat count must be non-negative - JavaScript

RangeError: repeat count must be non-negative
=============================================

 The JavaScript exception "repeat count must be non-negative" occurs when the
 `String.prototype.repeat()` method is used with a `count`
 argument that is a negative number.

Message
-------
```

RangeError: Invalid count value: -1 (V8-based)
RangeError: repeat count must be non-negative (Firefox)
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, +∞).

Examples
--------

### Invalid cases

```js
"abc".repeat(-1); // 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()`


Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript

Warning: -file- is being assigned a //# sourceMappingURL, but already has one
=============================================================================

The JavaScript warning "-file- is being assigned a //# sourceMappingURL, but already has one." occurs when a source map has been specified more than once for a given JavaScript source.

Message
-------
```

Warning: -file- is being assigned a //# sourceMappingURL, but already has one.
```

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

A warning. JavaScript execution won't be halted.

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

A source map has been specified more than once for a given JavaScript source.

JavaScript sources are often combined and minified to make delivering them from the server more efficient. With source maps, the debugger can map the code being executed to the original source files. There are two ways to assign a source map, either by using a comment or by setting a header to the JavaScript file.

Examples
--------

### Setting source maps

Setting a source map by using a comment in the file:

```js
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
```

Or, alternatively, you can set a header to your JavaScript file:

```http
X-SourceMap: /path/to/file.js.map
```

See also
--------

* Use a source map in the Firefox source docs
* Introduction to JavaScript source maps on developer.chrome.com (2012)


TypeError: can't define property "x": "obj" is not extensible - JavaScript

TypeError: can't define property "x": "obj" is not extensible
=============================================================

 The JavaScript exception "can't define property "x": "obj" is not extensible" occurs
 when `Object.preventExtensions()` marked an object as no longer extensible,
 so that it will never have properties beyond the ones it had at the time it was marked
 as non-extensible.

Message
-------
```

TypeError: Cannot add property x, object is not extensible (V8-based)
TypeError: Cannot define property x, object is not extensible (V8-based)
TypeError: can't define property "x": Object is not extensible (Firefox)
TypeError: Attempting to define property on object that is not extensible. (Safari)
```

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

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

 Usually, an object is extensible and new properties can be added to it. However, in
 this case `Object.preventExtensions()` marked an object as no longer
 extensible, so that it will never have properties beyond the ones it had at the time it
 was marked as non-extensible.

Examples
--------

### Adding new properties to a non-extensible objects

 In strict mode,
 attempting to add new properties to a non-extensible object throws a
 `TypeError`. In sloppy mode, the addition of the "x" property is silently
 ignored.

```js
"use strict";

const obj = {};
Object.preventExtensions(obj);

obj.x = "foo";
// TypeError: can't define property "x": Object is not extensible
```

 In both, strict mode and
 sloppy mode, a call to `Object.defineProperty()` throws when adding a new
 property to a non-extensible object.

```js
const obj = {};
Object.preventExtensions(obj);

Object.defineProperty(obj, "x", { value: "foo" });
// TypeError: can't define property "x": Object is not extensible
```

 To fix this error, you will either need to remove the call to
 `Object.preventExtensions()` entirely, or move it to a position so that the
 property is added earlier and only later the object is marked as non-extensible. Of
 course you can also remove the property that was attempted to be added, if you don't
 need it.

```js
"use strict";

const obj = {};
obj.x = "foo"; // add property first and only then prevent extensions

Object.preventExtensions(obj);
```

See also
--------

* `Object.preventExtensions()`


URIError: malformed URI sequence - JavaScript

URIError: malformed URI sequence
================================

 The JavaScript exception "malformed URI sequence" occurs when URI encoding or decoding
 wasn't successful.

Message
-------
```

URIError: URI malformed (V8-based)
URIError: malformed URI sequence (Firefox)
URIError: String contained an illegal UTF-16 sequence. (Safari)
```

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

`URIError`What went wrong?
----------------

 URI encoding or decoding wasn't successful. An argument given to either the
 `decodeURI`, `encodeURI`, `encodeURIComponent`, or
 `decodeURIComponent` function was not valid, so that the function was unable
 encode or decode properly.

Examples
--------

### Encoding

 Encoding replaces each instance of certain characters by one, two, three, or four
 escape sequences representing the UTF-8 encoding of the character. An
 `URIError` will be thrown if there is an attempt to encode a surrogate which
 is not part of a high-low pair, for example:

```js
encodeURI("\uD800");
// "URIError: malformed URI sequence"

encodeURI("\uDFFF");
// "URIError: malformed URI sequence"
```

A high-low pair is OK. For example:

```js
encodeURI("\uD800\uDFFF");
// "%F0%90%8F%BF"
```

### Decoding

 Decoding replaces each escape sequence in the encoded URI component with the character
 that it represents. If there isn't such a character, an error will be thrown:

```js
decodeURIComponent("%E0%A4%A");
// "URIError: malformed URI sequence"
```

With proper input, this should usually look like something like this:

```js
decodeURIComponent("JavaScript\_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript\_шеллы"
```

See also
--------

* `URIError`
* `decodeURI`
* `encodeURI`
* `encodeURIComponent`
* `decodeURIComponent`


SyntaxError: missing ] after element list - JavaScript

SyntaxError: missing ] after element list
=========================================

 The JavaScript exception "missing ] after element list" occurs when there is an error
 with the array initializer syntax somewhere. Likely there is a closing square bracket
 (`]`) or a comma (`,`) missing.

Message
-------
```

SyntaxError: missing ] after element list (Firefox)
SyntaxError: Unexpected token ';'. Expected either a closing ']' or a ',' following an array element. (Safari)
```

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

`SyntaxError`.

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

 There is an error with the array initializer syntax somewhere. Likely there is a
 closing square bracket (`]`) or a comma (`,`) missing.

Examples
--------

### Incomplete array initializer

```js
const list = [1, 2,

const instruments = [
  "Ukulele",
  "Guitar",
  "Piano",
};

const data = [{ foo: "bar" } { bar: "foo" }];
```

Correct would be:

```js
const list = [1, 2];

const instruments = ["Ukulele", "Guitar", "Piano"];

const data = [{ foo: "bar" }, { bar: "foo" }];
```

See also
--------

* `Array`


TypeError: "x" is not a non-null object - JavaScript

TypeError: "x" is not a non-null object
=======================================

 The JavaScript exception "is not a non-null object" occurs when an object is expected
 somewhere and wasn't provided. `null` is not an object and won't work.

Message
-------
```

TypeError: Property description must be an object: x (V8-based)
TypeError: Property descriptor must be an object, got "x" (Firefox)
TypeError: Property description must be an object. (Safari)

TypeError: Invalid value used in weak set (V8-based)
TypeError: WeakSet value must be an object, got "x" (Firefox)
TypeError: Attempted to add a non-object value to a WeakSet (Safari)
```

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

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

 An object is expected somewhere and wasn't provided. `null` is not an
 object and won't work. You must provide a proper object in the given situation.

Examples
--------

### Property descriptor expected

 When methods like `Object.create()` or
 `Object.defineProperty()` and `Object.defineProperties()` are
 used, the optional descriptor parameter expects a property descriptor object. Providing
 no object (like just a number), will throw an error:

```js
Object.defineProperty({}, "key", 1);
// TypeError: 1 is not a non-null object

Object.defineProperty({}, "key", null);
// TypeError: null is not a non-null object
```

A valid property descriptor object might look like this:

```js
Object.defineProperty({}, "key", { value: "foo", writable: false });
```

### WeakMap and WeakSet objects require object or symbol keys

`WeakMap` and `WeakSet` objects store object or symbol keys. You can't
 use other types as keys.

```js
const ws = new WeakSet();
ws.add("foo");
// TypeError: "foo" is not a non-null object
```

Use objects instead:

```js
ws.add({ foo: "bar" });
ws.add(window);
```

See also
--------

* `Object.create()`
* `Object.defineProperty()`
* `Object.defineProperties()`
* `WeakMap`
* `WeakSet`


SyntaxError: invalid regular expression flag "x" - JavaScript

SyntaxError: invalid regular expression flag "x"
================================================

The JavaScript exception "invalid regular expression flag" occurs when the flags in a regular expression contain any flag that is not one of: `d`, `g`, `i`, `m`, `s`, `u`, `v`, or `y`.

It may also be raised if the expression contains more than one instance of a valid flag.

Message
-------
```

SyntaxError: Invalid regular expression flags (V8-based)
SyntaxError: invalid regular expression flag x (Firefox)
SyntaxError: Invalid regular expression: invalid flags (Safari)
```

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

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

The regular expression contains invalid flags, or valid flags have been used more than once in the expression.

The valid (allowed) flags are `d`, `g`, `i`, `m`, `s`, `u`, `v`, and `y`. They are introduced in more detail in Regular expressions > Advanced searching with flags.

Examples
--------

 In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash.
 Regular expression flags can be used separately or together in any order.
 This syntax shows how to declare the flags using the regular expression literal:

```js
const re = /pattern/flags;
```

They can also be defined in the constructor function of the `RegExp` object (second parameter):

```js
const re = new RegExp("pattern", "flags");
```

Here is an example showing use of only correct flags.

```js
/foo/g;
/foo/gims;
/foo/uy;
```

Below is an example showing the use of some invalid flags `b`, `a` and `r`:

```js
/foo/bar;

// SyntaxError: invalid regular expression flag "b"
```

The code below is incorrect, because `W`, `e` and `b` are not valid flags.

```js
const obj = {
  url: /docs/Web,
};

// SyntaxError: invalid regular expression flag "W"
```

 An expression containing two slashes is interpreted as a regular expression literal.
 Most likely the intent was to create a string literal, using single or double quotes as shown below:

```js
const obj = {
  url: "/docs/Web",
};
```

See also
--------

* Regular expressions guide


TypeError: "x" is not a function - JavaScript

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

 The JavaScript exception "is not a function" occurs when there was an attempt to call a
 value from a function, but the value is not actually a function.

Message
-------
```

TypeError: "x" is not a function. (V8-based & Firefox & Safari)
```

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

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

 It attempted to call a value from a function, but the value is not actually a function.
 Some code expects you to provide a function, but that didn't happen.

 Maybe there is a typo in the function name? Maybe the object you are calling the method
 on does not have this function? For example, JavaScript `Objects` have no
 `map` function, but the JavaScript `Array` object does.

 There are many built-in functions in need of a (callback) function. You will have to
 provide a function in order to have these methods working properly:

* When working with `Array` or `TypedArray` objects:
    + `Array.prototype.every()`, `Array.prototype.some()`,
     `Array.prototype.forEach()`, `Array.prototype.map()`,
     `Array.prototype.filter()`, `Array.prototype.reduce()`,
     `Array.prototype.reduceRight()`, `Array.prototype.find()`
* When working with `Map` and `Set` objects:
    + `Map.prototype.forEach()` and `Set.prototype.forEach()`
Examples
--------

### A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

```js
const x = document.getElementByID("foo");
// TypeError: document.getElementByID is not a function
```

The correct function name is `getElementById`:

```js
const x = document.getElementById("foo");
```

### Function called on the wrong object

 For certain methods, you have to provide a (callback) function and it will work on
 specific objects only. In this example, `Array.prototype.map()` is used,
 which will work with `Array` objects only.

```js
const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num \* 2;
});

// TypeError: obj.map is not a function
```

Use an array instead:

```js
const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num \* 2;
}); // [2, 8, 18]
```

### Function shares a name with a pre-existing property

 Sometimes when making a class, you may have a property and a function with the same
 name. Upon calling the function, the compiler thinks that the function ceases to exist.

```js
function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
```

Use a different property name instead:

```js
function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; //Using this.dogName instead of .name
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
```

### Using parenthese for multiplication

In math, you can write 2 × (3 + 5) as 2\*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

```js
const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function
```

You can correct the code by adding a `*` operator:

```js
const sixteen = 2 \* (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16
```

### Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (`helpers.js`)

```js
const helpers = function () {};

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
};

export default helpers;
```

The correct import usage (`App.js`):

```js
import helpers from "./helpers";
```

See also
--------

* Functions


SyntaxError: Unexpected '#' used outside of class body - JavaScript

SyntaxError: Unexpected '#' used outside of class body
======================================================

 The JavaScript exception "Unexpected '#' used outside of class body" occurs when a hash
 ("#") is encountered in an unexpected context, most notably
 outside of a class declaration.
 Hashes are valid at the beginning of a file as a hashbang comment,
 or inside of a class as part of a private field. You may encounter this error if you forget
 the quotation marks when trying to access a DOM identifier as well.

Message
-------
```

SyntaxError: Unexpected '#' used outside of class body.
```

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

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

 We encountered a `#` somewhere unexpected. This may be due to code moving around and no
 longer being part of a class, a hashbang comment found on a line other than the first
 line of a file, or accidentally forgetting the quotation marks around a DOM identifier.

Examples
--------

### Missing quotation marks

For each case, there might be something slightly wrong. For example

```js
document.querySelector(#some-element)
```

This can be fixed via

```js
document.querySelector("#some-element");
```

### Outside of a class

```js
class ClassWithPrivateField {
  #privateField;

  constructor() {}
}

this.#privateField = 42;
```

This can be fixed by moving the private field back into the class

```js
class ClassWithPrivateField {
  #privateField;

  constructor() {
    this.#privateField = 42;
  }
}
```

See also
--------

* `SyntaxError`


TypeError: invalid Array.prototype.sort argument - JavaScript

TypeError: invalid Array.prototype.sort argument
================================================

The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of `Array.prototype.sort()` isn't either `undefined` or a function which compares its operands.

Message
-------
```

TypeError: The comparison function must be either a function or undefined (V8-based)
TypeError: invalid Array.prototype.sort argument (Firefox)
TypeError: Array.prototype.sort requires the comparator argument to be a function or undefined (Safari)
```

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

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

The argument of `Array.prototype.sort()` is expected to be either `undefined` or a function which compares its operands.

Examples
--------

### Invalid cases

```js
[1, 3, 2].sort(5); // TypeError
```

### Valid cases

```js
[1, 3, 2].sort(); // [1, 2, 3]
[1, 3, 2].sort((a, b) => a - b); // [1, 2, 3]
```

See also
--------

* `Array.prototype.sort()`


SyntaxError: unlabeled break must be inside loop or switch - JavaScript

SyntaxError: unlabeled break must be inside loop or switch
==========================================================

The JavaScript exception "unlabeled break must be inside loop or switch" occurs when a `break` statement is not inside a loop or a `switch` statement.

Message
-------
```

SyntaxError: Illegal break statement (V8-based)
SyntaxError: unlabeled break must be inside loop or switch (Firefox)
SyntaxError: 'break' is only valid inside a switch or loop statement. (Safari)
```

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

`SyntaxError`.

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

`break` statements can be used to exit a loop or a `switch` statement, and using them elsewhere is a syntax error. Alternatively, you can provide a label to the `break` statement to break out of any statement with that label — however, if the label does not reference a containing statement, another error SyntaxError: label not found will be thrown.

Examples
--------

### Unsyntactic break

`break` cannot be used outside `switch` or loops.

```js
let score = 0;

function increment() {
  if (score === 100)
    break; // SyntaxError: unlabeled break must be inside loop or switch
  }
  score++;
}
```

Maybe instead of `break`, you intend to use `return` to early-terminate a function.

```js
let score = 0;

function increment() {
  if (score === 100) {
    return;
  }
  score++;
}
```

### Using break in callbacks

`break` cannot be used in callbacks, even if the callback is called from a loop.

```js
let containingIndex = 0;
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

while (containingIndex < matrix.length) {
  matrix[containingIndex].forEach((value) => {
    if (value === 5) {
      break; // SyntaxError: unlabeled break must be inside loop or switch
    }
  });
  containingIndex++;
}
```

Instead, refactor the code so the `break` is used outside the callback.

```js
let containingIndex = 0;
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

outer: while (containingIndex < matrix.length) {
  for (const value of matrix[containingIndex]) {
    if (value === 5) {
      break outer;
    }
  }
  containingIndex++;
}
```

```js
let containingIndex = 0;
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

while (containingIndex < matrix.length) {
  if (matrix[containingIndex].includes(5)) {
    break;
  }
  containingIndex++;
}
```

There's no way to early-terminate a `forEach()` loop. You can use `some()` instead, or convert it to a `for...of` loop.

```js
array.forEach((value) => {
  if (value === 5) {
    break; // SyntaxError: unlabeled break must be inside loop or switch
  }
  // do something with value
});
```

```js
array.some((value) => {
  if (value === 5) {
    return true;
  }
  // do something with value
  return false;
});
```

```js
for (const value of array) {
  if (value === 5) {
    break;
  }
  // do something with value
}
```

See also
--------

* `break`


SyntaxError: missing ; before statement - JavaScript

SyntaxError: missing ; before statement
=======================================

 The JavaScript exception "missing ; before statement" occurs when there is a semicolon (`;`)
 missing somewhere and can't be added
 by automatic semicolon insertion (ASI).
 You need to provide a semicolon, so that JavaScript can parse the source code correctly.

Message
-------
```

SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)
```

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

`SyntaxError`.

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

 There is a semicolon (`;`) missing somewhere. JavaScript statements must
 be terminated with semicolons. Some of them are affected
 by automatic semicolon insertion (ASI),
 but in this case you need to provide a semicolon,
 so that JavaScript can parse the source code correctly.

 However, oftentimes, this error is only a consequence of another error, like not
 escaping strings properly, or using `var` wrongly. You might also have too
 many parenthesis somewhere. Carefully check the syntax when this error is thrown.

Examples
--------

### Unescaped strings

 This error can occur easily when not escaping strings properly and the JavaScript
 engine is expecting the end of your string already. For example:

```js
const foo = 'Tom's bar';
// SyntaxError: missing ; before statement
```

You can use double quotes, or escape the apostrophe:

```js
const foo = "Tom's bar";
// OR
const foo = 'Tom\'s bar';
```

### Declaring properties with keyword

 You **cannot** declare properties of an object or array with a
 `let`, `const`, or `var` declaration.

```js
const obj = {};
const obj.foo = "hi"; // SyntaxError missing ; before statement

const array = [];
const array[0] = "there"; // SyntaxError missing ; before statement
```

Instead, omit the keyword:

```js
const obj = {};
obj.foo = "hi";

const array = [];
array[0] = "there";
```

### Bad keywords

 If you come from another programming language, it is also common to use keywords that
 don't mean the same or have no meaning at all in JavaScript:

```js
def print(info) {
  console.log(info);
} // SyntaxError missing ; before statement
```

Instead, use `function` instead of `def`:

```js
function print(info) {
  console.log(info);
}
```

See also
--------

* Automatic semicolon insertion (ASI)
* Statements and declarations


ReferenceError: can't access lexical declaration 'X' before initialization - JavaScript

ReferenceError: can't access lexical declaration 'X' before initialization
==========================================================================

 The JavaScript exception "can't access lexical declaration `*variable*' before initialization" occurs when a lexical variable was accessed before it was initialized.
 This happens within any block statement, when `let` or `const` variables are accessed before the place where they are declared is executed.

Message
-------
```

ReferenceError: Cannot access 'X' before initialization (V8-based)
ReferenceError: can't access lexical declaration 'X' before initialization (Firefox)
ReferenceError: Cannot access uninitialized variable. (Safari)
```

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

`ReferenceError`What went wrong?
----------------

 A lexical variable was accessed before it was initialized.
 This happens within any block statement, when variables declared with `let` or `const` are accessed before the place where they are declared has been executed.

 Note that it is the execution order of access and variable declaration that matters, not the order in which the statements appear in the code.
 For more information, see the description of Temporal Dead Zone.

This issue does not occur for variables declared using `var`, because they are initialized with a default value of `undefined` when they are hoisted.

This error can also occur in cyclic imports when a module uses a variable that depends on the module itself being evaluated.

Examples
--------

### Invalid cases

 In this case, the variable `foo` is accessed before it is declared.
 At this point foo has not been initialized with a value, so accessing the variable throws a reference error.

```js
function test() {
  // Accessing the 'const' variable foo before it's declared
  console.log(foo); // ReferenceError: foo is not initialized
  const foo = 33; // 'foo' is declared and initialized here using the 'const' keyword
}

test();
```

In this example, the imported variable `a` is accessed but is uninitialized, because the evaluation of `a.js` is blocked by the evaluation of the current module `b.js`.

```js
// -- a.js (entry module) --
import { b } from "./b.js";

export const a = 2;

// -- b.js --
import { a } from "./a.js";

console.log(a); // ReferenceError: Cannot access 'a' before initialization
export const b = 1;
```

### Valid cases

In the following example, we correctly declare a variable using the `const` keyword before accessing it.

```js
function test() {
  // Declaring variable foo
  const foo = 33;
  console.log(foo); // 33
}
test();
```

In this example, the imported variable `a` is asynchronously accessed, so both modules are evaluated before the access to `a` occurs.

```js
// -- a.js (entry module) --
import { b } from "./b.js";

export const a = 2;

// -- b.js --
import { a } from "./a.js";

setTimeout(() => {
  console.log(a); // 2
}, 10);
export const b = 1;
```

See also
--------

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


RangeError: BigInt negative exponent - JavaScript

RangeError: BigInt negative exponent
====================================

The JavaScript exception "BigInt negative exponent" occurs when a `BigInt` is raised to the power of a negative BigInt value.

Message
-------
```

RangeError: Exponent must be positive (V8-based)
RangeError: BigInt negative exponent (Firefox)
RangeError: Negative exponent is not allowed (Safari)
```

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

`RangeError`.

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

The exponent of an exponentiation operation must be positive. Since negative exponents would take the reciprocal of the base, the result will be between -1 and 1 in almost all cases, which gets rounded to `0n`. To catch mistakes, negative exponents are not allowed. Check if the exponent is non-negative before doing exponentiation.

Examples
--------

### Using a negative BigInt as exponent

```js
const a = 1n;
const b = -1n;
const c = a \*\* b;
// RangeError: BigInt negative exponent
```

Instead, check if the exponent is negative first, and either issue an error with a better message, or fallback to a different value, like `0n` or `undefined`.

```js
const a = 1n;
const b = -1n;
const quotient = b >= 0n ? a \*\* b : 0n;
```

See also
--------

* `BigInt`
* Exponentiation (`**`)


SyntaxError: missing variable name - JavaScript

SyntaxError: missing variable name
==================================

 The JavaScript exception "missing variable name" is a common error.
 It is usually caused by omitting a variable name or a typographic error.

Message
-------
```

SyntaxError: missing variable name (Firefox)
SyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)
```

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

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

 A variable is missing a name. The cause is most likely a typo or a forgotten variable name.
 Make sure that you've provided the name of the variable before the `=` sign.

When declaring multiple variables at the same time, make sure that the previous lines/declaration does not end with a comma instead of a semicolon.

Examples
--------

### Missing a variable name

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

It is easy to forget to assign a name for your variable!

```js
const description = "foo";
```

### Reserved keywords can't be variable names

 There are a few variable names that are reserved keywords.
 You can't use these. Sorry :(

```js
const debugger = "whoop";
// SyntaxError: missing variable name
```

### Declaring multiple variables

 Pay special attention to commas when declaring multiple variables.
 Is there an excess comma, or did you use commas instead of semicolons?
 Did you remember to assign values for all your `const` variables?

```js
let x, y = "foo",
const z, = "foo"

const first = document.getElementById("one"),
const second = document.getElementById("two"),

// SyntaxError: missing variable name
```

The fixed version:

```js
let x,
  y = "foo";
const z = "foo";

const first = document.getElementById("one");
const second = document.getElementById("two");
```

### Arrays

`Array` literals in JavaScript need square brackets around the values.
 This won't work:

```js
const arr = 1,2,3,4,5;
// SyntaxError: missing variable name
```

This would be correct:

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

See also
--------

* Lexical grammar
* `var`
* Grammar and types guide