• Skip to main content
  • Select language
  • Skip to search

TypeError: invalid assignment to const "x"

Const and immutability, what went wrong.

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

Invalid redeclaration

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

Fixing the error

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

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

const , let or var ?

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

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

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

But you can mutate the properties in a variable:

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy." href="Property_access_denied.html">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing variable name
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: cyclic object value
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting a property that has only a getter
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

JavaScript const Keyword Explained with Examples

You write the keyword, followed it up with a variable name, the assignment = operator, and the variable’s value:

The const Keyword Only Prevents Reassignment

When to use the const keyword.

The answer is when you need to declare a variable that will never change during the lifecycle of your program.

Take your skills to the next level ⚡️

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Error Object Complete Reference

JS Range Error

  • JavaScript RangeError - Invalid date
  • JavaScript RangeError - Repeat count must be non-negative

JS Reference Error

  • JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization
  • JavaScript ReferenceError - Invalid assignment left-hand side
  • JavaScript ReferenceError - Assignment to undeclared variable
  • JavaScript ReferenceError - Reference to undefined property "x"
  • JavaScript ReferenceError - variable is not defined
  • JavaScript ReferenceError Deprecated caller or arguments usage

JS Syntax Error

  • JavaScript SyntaxError - Illegal character
  • JavaScript SyntaxError - Identifier starts immediately after numeric literal
  • JavaScript SyntaxError - Function statement requires a name
  • JavaScript SyntaxError - Missing } after function body
  • JavaScript SyntaxError - Missing } after property list
  • JavaScript SyntaxError - Missing variable name
  • JavaScript SyntaxError - Missing ] after element list
  • JavaScript SyntaxError - Invalid regular expression flag "x"
  • JavaScript SyntaxError "variable" is a reserved identifier
  • JavaScript SyntaxError - Missing ':' after property id
  • JavaScript SyntaxError - Missing ) after condition
  • JavaScript SyntaxError - Missing formal parameter
  • JavaScript SyntaxError - Missing ; before statement
  • JavaScript SyntaxError - Missing = in const declaration
  • JavaScript SyntaxError - Missing name after . operator
  • JavaScript SyntaxError - Redeclaration of formal parameter "x"
  • JavaScript SyntaxError - Missing ) after argument list
  • JavaScript SyntaxError - Return not in function
  • JavaScript SyntaxError: Unterminated string literal
  • JavaScript SyntaxError - Applying the 'delete' operator to an unqualified name is deprecated
  • JavaScript SyntaxError - Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • JavaScript SyntaxError - Malformed formal parameter
  • JavaScript SyntaxError - "0"-prefixed octal literals and octal escape sequences are deprecated
  • JavaScript SyntaxError - Test for equality (==) mistyped as assignment (=)?
  • JavaScript SyntaxError - "x" is not a legal ECMA-262 octal constant

JS Type Error

  • JavaScript TypeError - "X" is not a non-null object
  • JavaScript TypeError - "X" is not a constructor
  • JavaScript TypeError - "X" has no properties
  • JavaScript TypeError - "X" is (not) "Y"
  • JavaScript TypeError - "X" is not a function
  • JavaScript TypeError - 'X' is not iterable
  • JavaScript TypeError - More arguments needed
  • JavaScript TypeError - "X" is read-only
  • JavaScript TypeError - Reduce of empty array with no initial value
  • JavaScript TypeError - Can't assign to property "X" on "Y": not an object
  • JavaScript TypeError - Can't access property "X" of "Y"
  • JavaScript TypeError - Can't define property "X": "Obj" is not extensible
  • JavaScript TypeError - X.prototype.y called on incompatible type
  • JavaScript TypeError - Invalid assignment to const "X"
  • JavaScript TypeError - Property "X" is non-configurable and can't be deleted
  • JavaScript TypeError - Can't redefine non-configurable property "x"
  • JavaScript TypeError - Variable "x" redeclares argument
  • JavaScript TypeError - Setting getter-only property "x"
  • JavaScript TypeError - Invalid 'instanceof' operand 'x'
  • JavaScript TypeError - Invalid Array.prototype.sort argument
  • JavaScript TypeError - Cyclic object value
  • JavaScript TypeError - Can't delete non-configurable array element

JS Other Errors

  • JavaScript URIError | Malformed URI Sequence
  • JavaScript Warning - Date.prototype.toLocaleFormat is deprecated
  • Logging Script Errors in JavaScript

JS Error Instance

  • JavaScript Error message Property
  • JavaScript Error name Property
  • JavaScript Error.prototype.toString() Method

JavaScript TypeError – Invalid assignment to const “X”

This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared.

Error Type:

Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution. 

Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred.

Output(in console):

Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred.

Please Login to comment...

Similar reads.

  • JavaScript-Errors
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Typeerror assignment to constant variable

Doesn’t know how to solve the “Typeerror assignment to constant variable” error in Javascript?

Don’t worry because this article will help you to solve that problem

In this article, we will discuss the Typeerror assignment to constant variable , provide the possible causes of this error, and give solutions to resolve the error.

What is Typeerror assignment to constant variable?

“Typeerror assignment to constant variable” is an error message that can occur in JavaScript code.

It means that you have tried to modify the value of a variable that has been declared as a constant.

When we try to reassign greeting to a different value (“Hi”) , we will get the error:

because we are trying to change the value of a constant variable.

How does Typeerror assignment to constant variable occurs ?

In JavaScript, constants are variables whose values cannot be changed once they have been assigned.

Here is an example :

In this example, we declared a constant variable age and assigned it the value 30 .

If you declare an object using the const keyword, you can still modify the properties of the object.

For example:

In this example, we declared a constant object person with two properties ( name and age ).

In this example, we declared a constant variable name and assigned it the value John .

Now let’s fix this error.

Typeerror assignment to constant variable – Solutions

Solution 1: declare the variable using the let or var keyword:.

If you need to modify the value of a variable, you should declare it using the let or var keyword instead of const .

Just like the example below:

Solution 2: Use an object or array instead of a constant variable:

If you need to modify the properties of a variable, you can use an object or array instead of a constant variable.

Solution 3: Declare the variable outside of strict mode:

Solution 4: use the const keyword and use a different name :, solution 5: declare a const variable with the same name in a different scope :.

But with a different value, without modifying the original constant variable.

You can create a new constant variable with the same name, without modifying the original constant variable.

So those are the alternative solutions that you can use to fix the TypeError.

In conclusion, in this article, we discussed   “Typeerror assignment to constant variable” , provided its causes and give solutions that resolve the error.

We’re happy to help you.

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared.

The constant's name, which can be any legal identifier .

The constant's value. This can be any legal expression , including a function expression.

The Destructuring Assignment syntax can also be used to declare variables.

Description

This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables.

An initializer for a constant is required. You must specify its value in the same statement in which it's declared. (This makes sense, given that it can't be changed later.)

The const creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

All the considerations about the " temporal dead zone " apply to both let and const .

A constant cannot share its name with a function or a variable in the same scope.

Basic const usage

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.

Block scoping

It's important to note the nature of block scoping.

const needs to be initialized

Const in objects and arrays.

const also works on objects and arrays.

Specifications

Specification

What went wrong?

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

Invalid redeclaration

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

Fixing the error

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

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

const , let or var ?

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

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

const and immutability

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

But you can mutate the properties in a variable:

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.ListFormat
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical operators
  • Object initializer
  • Operator precedence
  • (currently at stage 1) allows the creation of chained function calls in a readable manner. Basically, the pipeline operator provides syntactic sugar on a function call with a single argument allowing you to write">Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' operand 'x'
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • X.prototype.y called on incompatible type
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

TekTutorialsHub-Logo

JavaScript Const

JavaScript constants are variables , whose values cannot be modified after initialization. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript .

Table of Contents

Declaring a const

The initial value is a must, const is block-scoped, we cannot modify its value, const and object, cannot access before the declaration, cannot redeclare a const..

We declare constants using the keyword const keyword

MaxAllowed=100 ;

The initial value of the const must be specified along with the declaration.

maxValue=100;     //Ok maxValue1;        //Uncaught SyntaxError: Missing initializer in const declaration

The const is similar to the let keyword. They are local to the code block in which we declare them.

Rate = 10;       //global scope (true) { const Rate = 8;     //its scope is limited to the if block console.log(Rate);  //Prints 8 .log(Rate);    //Prints 10

We can assign a value to the const variable at the time of declaration. Once initialized, we cannot modify its value. So if you try to assign a new value to a constant it results in an error.

MaxTry=10 ; =5;            //Uncaught TypeError: Assignment to constant variable.

Similarly, if the const is an object.

emp = { id:1, name:"Rahul"} = {id:2, name:"Sachin"}      //code1.js:2 Uncaught TypeError: Assignment to constant variable.

You cannot assign new content to a const variable. But if the content is an object, then we can modify the object itself.

The following example throws the error Assignment to constant variable when we try to assign a new object to obj variable.

obj= { firstName: "Allie", lastName: "Grater" ; = { firstName: "Jack", lastName: "Ferguson" }

However, you can change the properties of the object itself.

obj = { firstName: "Allie", lastName: "Grater" ; .firstName= "Jack", .lastName= "Ferguson"

To understand why you need to understand the difference between value types & reference types

There are two types of data types in JavaScript. One is value types (primitive values) & the other one is reference types. The types string, number, Bigint, boolean, undefined, symbol, and null are value types. Everything else is reference types. The primary difference between value types & Reference types is how JavaScript stores them in memory.

num=10 obj= { firstName: "Allie", lastName: "Grater" ;

JavaScript stores the value types in the variable itself. But in the case of reference type variables, they do not store the value. But they store the reference to the memory location where JavaScript stores the actual values.

JavaScript Const and Objects

Both the code below throws Uncaught TypeError: Assignment to constant variable error as we are assigning a new value.

  = 20;         obj  = {    firstName: "Jack",     lastName: "Ferguson" };  

But you can change the object itself.

.firstName= "Jack", .lastName= "Ferguson"

The following is an example using arrays.

cities =['Delhi','Mumbai','Chennai'] = ['New york','London','Sydney']       //Error here .splice(0,3);                        //allowed .push('New york','London','Sydney')  //allowed .log(cities);

Accessing the const before the initialization results in a ReferenceError . The variable in a “ temporal dead zone ” from the start of the block until the initialization. You can read more about it from Hoisting in JavaScript .

.log(City);     //Uncaught ReferenceError: Cannot access 'City' before initialization City  = "DELHI";

Trying to redeclare constant throws the following error. Uncaught SyntaxError: Identifier ‘MaxTry’ has already been declared”.

MaxTry=10; .log(MaxTry); MaxTry=100;   //Uncaught SyntaxError: Identifier 'MaxTry' has already been declared .log(MaxTry);

You can use const to declare values that do not change. Use let for everything else. But always remember the fact that if const points to an object, then you can change its properties.

  • JavaScript Tutorial

JavaScript Hello World Example

  • Syntax and Rules
  • JavaScript Identifiers
  • Keywords & Reserved Words
  • JavaScript Variables
  • Constants in JavaScript
  • Let, var & const

Related Posts

Introduction to JavaScript

Introduction to Javascript

Hello World in JavaScript

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • [email protected]
  • 🇮🇳 +91 (630)-411-6234
  • Reactjs Development Services
  • Flutter App Development Services
  • Mobile App Development Services

Web Development

Mobile app development, nodejs typeerror: assignment to constant variable.

Published By: Divya Mahi

Published On: November 17, 2023

Published In: Development

Grasping and Fixing the 'NodeJS TypeError: Assignment to Constant Variable' Issue

Introduction.

Node.js, a powerful platform for building server-side applications, is not immune to errors and exceptions. Among the common issues developers encounter is the “NodeJS TypeError: Assignment to Constant Variable.” This error can be a source of frustration, especially for those new to JavaScript’s nuances in Node.js. In this comprehensive guide, we’ll explore what this error means, its typical causes, and how to effectively resolve it.

Understanding the Error

In Node.js, the “TypeError: Assignment to Constant Variable” occurs when there’s an attempt to reassign a value to a variable declared with the const keyword. In JavaScript, const is used to declare a variable that cannot be reassigned after its initial assignment. This error is a safeguard in the language to ensure the immutability of variables declared as constants.

Diving Deeper

This TypeError is part of JavaScript’s efforts to help developers write more predictable code. Immutable variables can prevent bugs that are hard to trace, as they ensure that once a value is set, it cannot be inadvertently changed. However, it’s important to distinguish between reassigning a variable and modifying an object’s properties. The latter is allowed even with variables declared with const.

Common Scenarios and Fixes

Example 1: reassigning a constant variable.

Javascript:

Fix: Use let if you need to reassign the variable.

Example 2: Modifying an Object's Properties

Fix: Modify the property instead of reassigning the object.

Example 3: Array Reassignment

Fix: Modify the array’s contents without reassigning it.

Example 4: Within a Function Scope

Fix: Declare a new variable or use let if reassignment is needed.

Example 5: In Loops

Fix: Use let for variables that change within loops.

Example 6: Constant Function Parameters

Fix: Avoid reassigning function parameters directly; use another variable.

Example 7: Constants in Conditional Blocks

Fix: Use let if the variable needs to change.

Example 8: Reassigning Properties of a Constant Object

Fix: Modify only the properties of the object.

Strategies to Prevent Errors

Understand const vs let: Familiarize yourself with the differences between const and let. Use const for variables that should not be reassigned and let for those that might change.

Code Reviews: Regular code reviews can catch these issues before they make it into production. Peer reviews encourage adherence to best practices.

Linter Usage: Tools like ESLint can automatically detect attempts to reassign constants. Incorporating a linter into your development process can prevent such errors.

Best Practices

Immutability where Possible: Favor immutability in your code to reduce side effects and bugs. Normally use const to declare variables, and use let only if you need to change their values later .

Descriptive Variable Names: Use clear and descriptive names for your variables. This practice makes it easier to understand when a variable should be immutable.

Keep Functions Pure: Avoid reassigning or modifying function arguments. Keeping functions pure (not causing side effects) leads to more predictable and testable code.

The “NodeJS TypeError: Assignment to Constant Variable” error, while common, is easily avoidable. By understanding JavaScript’s variable declaration nuances and adopting coding practices that embrace immutability, developers can write more robust and maintainable Node.js applications. Remember, consistent coding standards and thorough code reviews are your best defense against common errors like these.

Related Articles

March 13, 2024

Expressjs Error: 405 Method Not Allowed

March 11, 2024

Expressjs Error: 502 Bad Gateway

I’m here to assist you.

Something isn’t Clear? Feel free to contact Us, and we will be more than happy to answer all of your questions.

Java2Blog

Java Tutorials

  • Java Interview questions
  • Java 8 Stream

Data structure and algorithm

  • Data structure in java
  • Data structure interview questions

Spring tutorials

  • Spring tutorial
  • Spring boot tutorial
  • Spring MVC tutorial
  • Spring interview questions
  • keyboard_arrow_left Previous

[Fixed] TypeError: Assignment to constant variable in JavaScript

Table of Contents

Problem : TypeError: Assignment to constant variable

Rename the variable, change variable type to let or var, check if scope is correct, const and immutability.

TypeError: Assignment to constant variable in JavaScript occurs when we try to reassign value to const variable. If we have declared variable with const , it can’t be reassigned.

Let’s see with the help of simple example.

country1 = "India"; = "china"; .log(country1);
= "china"; ^ : Assignment to constant variable. at Object.<anonymous> (HelloWorld.js:4:8) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11

Solution : TypeError: Assignment to constant variable

If you are supposed to declare another constant, just declare another name.

country1 = "India"; country2= "china"; .log(country1); .log(country2);

If you are supposed to change the variable value, then it shouldn’t be declared as constant.

Change type to either let or var.

country1 = "India"; = "China"; .log(country1);

You can check if scope is correct as you can have different const in differnt scopes such as function.

country1 = "India"; countryName() { country1= "China";

This is valid declaration as scope for country1 is different.

const declaration creates read only reference. It means that you can not reassign it. It does not mean that you can not change values in the object.

Let’s see with help of simple example:

country = { name : 'India' = { name : 'Bhutan' .log(country);
= { ^ : Assignment to constant variable. at Object.<anonymous> (HelloWorld.js:5:9) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11

But, you can change the content of country object as below:

country = { name : 'India' .name = 'Bhutan' .log(country);
name: 'Bhutan' }

That’s all about how to fix TypeError: Assignment to constant variable in javascript.

Was this post helpful?

Related posts:.

  • jQuery before() and insertBefore() example
  • jQuery append and append to example
  • Round to 2 decimal places in JavaScript
  • Convert Seconds to Hours Minutes Seconds in Javascript
  • [Solved] TypeError: toLowerCase is not a function in JavaScript
  • TypeError: toUpperCase is not a function in JavaScript
  • Remove First Character from String in JavaScript
  • Get Filename from Path in JavaScript
  • Write Array to CSV in JavaScript

Get String Between Two Characters in JavaScript

[Fixed] Syntaxerror: invalid shorthand property initializer in Javascript

Convert epoch time to Date in Javascript

typeerror assignment to constant

Follow Author

Related Posts

Get String between two characters in JavaScript

Table of ContentsUsing substring() MethodUsing slice() MethodUsing split() MethodUsing substr() Method 💡TL;DR Use the substring() method to get String between two characters in JavaScript. [crayon-6667e237312e4190266263/] [crayon-6667e237312e9174766524/] Here, we got String between , and ! in above example. Using substring() Method Use the substring() method to extract a substring that is between two specific characters from […]

typeerror assignment to constant

Return Boolean from Function in JavaScript

Table of ContentsUsing the Boolean() FunctionUse the Boolean() Function with Truthy/Falsy ValuesUsing Comparison OperatorUse ==/=== Operator to Get Boolean Using Booleans as ObjectsUse ==/=== Operator to Compare Two Boolean Objects Using the Boolean() Function To get a Boolean from a function in JavaScript: Create a function which returns a Boolean value. Use the Boolean() function […]

Create Array from 1 to 100 in JavaScript

Table of ContentsUse for LoopUse Array.from() with Array.keys()Use Array.from() with Array ConstructorUse Array.from() with length PropertyUse Array.from() with fill() MethodUse ... Operator Use for Loop To create the array from 1 to 100 in JavaScript: Use a for loop that will iterate over a variable whose value starts from 1 and ends at 100 while […]

Get Index of Max Value in Array in JavaScript

Table of ContentsUsing indexOf() with Math.max() MethodUsing for loopUsing reduce() FunctionUsing _.indexOf() with _.max() MethodUsing sort() with indexOf() Method Using indexOf() with Math.max() Method To get an index of the max value in a JavaScript array: Use the Math.max() function to find the maximum number from the given numbers. Here, we passed an array and […]

Update Key with New Value in JavaScript

Table of ContentsUsing Bracket NotationUpdate Single Key with New ValueUpdate Multiple Keys with New ValuesUsing Dot NotationUpdate Single Key with New ValueUpdate Multiple Keys with New ValuesUsing forEach() MethodUpdate All Keys with New ValuesUsing map() MethodUpdate All Keys with New Values Using Bracket Notation We can use bracket notation to update the key with the […]

Format Phone Number in JavaScript

Table of ContentsUsing match() MethodFormat Without Country CodeFormat with Country Code Using match() Method We use the match() method to format a phone number in JavaScript. Format Without Country Code To format the phone number without country code: Use the replace() method with a regular expression /\D/g to remove non-numeric elements from the phone number. […]

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Let’s be Friends

© 2020-22 Java2Blog Privacy Policy

关于“TypeError: Assignment to constant variable”的问题解决方案

typeerror assignment to constant

在项目开发过程中,在使用变量声明时,如果不注意,可能会造成类型错误 比如:

Uncaught (in promise) TypeError: Assignment to constant variable. 未捕获的类型错误:赋值给常量变量。

我们使用 const 定义了变量且存在初始值。 后面又给这个变量赋值,所以报错了。

ES6 标准引入了新的关键字 const 来定义常量, const 与 let 都具有块级作用域:

  • 使用 const 定义的常量,不能修改它的值,且定义的常量必须赋初值;
  • let 定义的是变量,可以进行变量赋值操作,且不需要赋初值。

这个错误就是因为我们修改了常量而引起的错误,虽然某些浏览器不报错,但是无效果!

将 const 改为 let 进行声明。

typeerror assignment to constant

“相关推荐”对你有帮助么?

typeerror assignment to constant

请填写红包祝福语或标题

typeerror assignment to constant

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

typeerror assignment to constant

A Definitive Guide to Handling Errors in JavaScript

Illustration of a person looking at a laptop that has miniature humans standing on it holding up red exclamation point signs.

Murphy’s law states that whatever can go wrong will eventually go wrong. This applies a tad too well in the world of programming. If you create an application, chances are you’ll create bugs and other issues. Errors in JavaScript are one such common issue!

A software product’s success depends on how well its creators can resolve these issues before hurting their users. And JavaScript , out of all  programming languages , is notorious for its average error handling design.

If you’re building a JavaScript application , there’s a high chance you’ll mess up with data types at one point or another. If not that, then you might end up replacing an undefined with a null or a triple equals operator ( === ) with a double equals operator ( == ).

It’s only human to make mistakes. This is why we will show you everything you need to know about handling errors in JavaScript.

This article will guide you through the basic errors in JavaScript and explain the various errors you might encounter. You’ll then learn how to identify and fix these errors. There are also a couple of tips to handle errors effectively in production environments.

Without further ado, let’s begin!

Check Out Our Video Guide to Handling JavaScript Errors

What are javascript errors.

Errors in programming refer to situations that don’t let a program function normally. It can happen when a program doesn’t know how to handle the job at hand, such as when trying to open a non-existent file or reaching out to a web-based API endpoint while there’s no network connectivity.

These situations push the program to throw errors to the user, stating that it doesn’t know how to proceed. The program collects as much information as possible about the error and then reports that it can not move ahead.

Intelligent programmers try to predict and cover these scenarios so that the user doesn’t have to figure out a technical error message like “404” independently. Instead, they show a much more understandable message: “The page could not be found.”

Errors in JavaScript are objects shown whenever a programming error occurs. These objects contain ample information about the type of the error, the statement that caused the error, and the stack trace when the error occurred. JavaScript also allows programmers to create custom errors to provide extra information when debugging issues.

Properties of an Error

Now that the definition of a JavaScript error is clear, it’s time to dive into the details.

Errors in JavaScript carry certain standard and custom properties that help understand the cause and effects of the error. By default, errors in JavaScript contain three properties:

  • message : A string value that carries the error message
  • name : The type of error that occurred (We’ll dive deep into this in the next section)
  • stack : The stack trace of the code executed when the error occurred.

Additionally, errors can also carry properties like columnNumber, lineNumber, fileName, etc., to describe the error better. However, these properties are not standard and may or may not be present in every error object generated from your JavaScript application.

Understanding Stack Trace

A stack trace is the list of method calls a program was in when an event such as an exception or a warning occurs. This is what a sample stack trace accompanied by an exception looks like:

The error “TypeError: Numeric argument is expected” is shown on a gray background with additional stack details.

As you can see, it starts by printing the error name and message, followed by a list of methods that were being called. Each method call states the location of its source code and the line at which it was invoked. You can use this data to navigate through your codebase and identify which piece of code is causing the error.

This list of methods is arranged in a stacked fashion. It shows where your exception was first thrown and how it propagated through the stacked method calls. Implementing a catch for the exception will not let it propagate up through the stack and crash your program. However, you might want to leave fatal errors uncaught to crash the program in some scenarios intentionally.

Errors vs Exceptions

Most people usually consider errors and exceptions as the same thing. However, it’s essential to note a slight yet fundamental difference between them.

To understand this better, let’s take a quick example. Here is how you can define an error in JavaScript:

And this is how the wrongTypeError object becomes an exception:

However, most people tend to use the shorthand form which defines error objects while throwing them:

This is standard practice. However, it’s one of the reasons why developers tend to mix up exceptions and errors. Therefore, knowing the fundamentals is vital even though you use shorthands to get your work done quickly.

Types of Errors in JavaScript

There’s a range of predefined error types in JavaScript. They are automatically chosen and defined by the JavaScript runtime whenever the programmer doesn’t explicitly handle errors in the application.

This section will walk you through some of the most common types of errors in JavaScript and understand when and why they occur.

A RangeError is thrown when a variable is set with a value outside its legal values range. It usually occurs when passing a value as an argument to a function, and the given value doesn’t lie in the range of the function’s parameters. It can sometimes get tricky to fix when using poorly documented third-party libraries since you need to know the range of possible values for the arguments to pass in the correct value.

Some of the common scenarios in which RangeError occurs are:

  • Trying to create an array of illegal lengths via the Array constructor.
  • Passing bad values to numeric methods like toExponential() , toPrecision() , toFixed() , etc.
  • Passing illegal values to string functions like normalize() .

ReferenceError

A ReferenceError occurs when something is wrong with a variable’s reference in your code. You might have forgotten to define a value for the variable before using it, or you might be trying to use an inaccessible variable in your code. In any case, going through the stack trace provides ample information to find and fix the variable reference that is at fault.

Some of the common reasons why ReferenceErrors occur are:

  • Making a typo in a variable name.
  • Trying to access block-scoped variables outside of their scopes.
  • Referencing a global variable from an external library (like $ from jQuery ) before it’s loaded.

SyntaxError

These errors are one of the simplest to fix since they indicate an error in the syntax of the code. Since JavaScript is a  scripting language that is interpreted rather than compiled, these are thrown when the app executes the script that contains the error. In the case of compiled languages, such errors are identified during compilation. Thus, the app binaries are not created until these are fixed.

Some of the common reasons why SyntaxErrors might occur are:

  • Missing inverted commas
  • Missing closing parentheses
  • Improper alignment of curly braces or other characters

It’s a good practice to use a linting tool in your IDE to identify such errors for you before they hit the browser.

TypeError is one of the most common errors in JavaScript apps. This error is created when some value doesn’t turn out to be of a particular expected type. Some of the common cases when it occurs are:

  • Invoking objects that are not methods.
  • Attempting to access properties of null or undefined objects
  • Treating a string as a number or vice versa

There are a lot more possibilities where a TypeError can occur. We’ll look at some famous instances later and learn how to fix them.

InternalError

The InternalError type is used when an exception occurs in the JavaScript runtime engine. It may or may not indicate an issue with your code.

More often than not, InternalError occurs in two scenarios only:

  • When a patch or an update to the JavaScript runtime carries a bug that throws exceptions (this happens very rarely)
  • When your code contains entities that are too large for the JavaScript engine (e.g. too many switch cases, too large array initializers, too much recursion)

The most appropriate approach to solve this error is to identify the cause via the error message and restructure your app logic, if possible, to eliminate the sudden spike of workload on the JavaScript engine.

URIError occurs when a global URI handling function such as decodeURIComponent is used illegally. It usually indicates that the parameter passed to the method call did not conform to URI standards and thus was not parsed by the method properly .

Diagnosing these errors is usually easy since you only need to examine the arguments for malformation.

An EvalError occurs when an error occurs with an eval() function call. The eval() function is used to execute JavaScript code stored in strings. However, since using the eval() function is highly discouraged due to security issues and the current ECMAScript specifications don’t throw the EvalError class anymore, this error type exists simply to maintain backward compatibility with legacy JavaScript code.

If you’re working on an older version of JavaScript, you might encounter this error. In any case, it’s best to investigate the code executed in the eval() function call for any exceptions.

Creating Custom Error Types

While JavaScript offers an adequate list of error type classes to cover for most scenarios, you can always create a new error type if the list doesn’t satisfy your requirements. The foundation of this flexibility lies in the fact that JavaScript allows you to throw anything literally with the throw command.

So, technically, these statements are entirely legal:

However, throwing a primitive data type doesn’t provide details about the error, such as its type, name, or the accompanying stack trace. To fix this and standardize the error handling process, the Error class has been provided. It’s also discouraged to use primitive data types while throwing exceptions.

You can extend the Error class to create your custom error class. Here is a basic example of how you can do this:

And you can use it in the following way:

And you can then identify it using the instanceof keyword:

Top 10 Most Common Errors in JavaScript

Now that you understand the common error types and how to create your custom ones, it’s time to look at some of the most common errors you’ll face when writing JavaScript code.

Check Out Our Video Guide to The Most Common JavaScript Errors

1. uncaught rangeerror.

This error occurs in Google Chrome under a few various scenarios. First, it can happen if you call a recursive function and it doesn’t terminate. You can check this out yourself in the Chrome Developer Console:

The error “Uncaught RangeError: Maximum call stack size exceeded” is shown on a red background beside a red cross icon with a recursive function’s code above it.

So to solve such an error, make sure to define the border cases of your recursive function correctly. Another reason why this error happens is if you have passed a value that is out of a function’s parameter’s range. Here’s an example:

The error “Uncaught RangeError: toExponential() argument must be between 0 and 100” is shown on a red background beside a red cross icon with a toExponential() function call above it.

The error message will usually indicate what is wrong with your code. Once you make the changes, it will be resolved.

num = 4. num.toExponential(2). Output: 4.00e+0.

2. Uncaught TypeError: Cannot set property

This error occurs when you set a property on an undefined reference. You can reproduce the issue with this code:

Here’s the output that you’ll receive:

The error “Uncaught TypeError: Cannot set properties of undefined” is shown on a red background beside a red cross icon with a list.count = 0 assignment above it.

To fix this error, initialize the reference with a value before accessing its properties. Here’s how it looks when fixed:

Setting list.count = 10 after initializing list with {} due to which the output is 10.

3. Uncaught TypeError: Cannot read property

This is one of the most frequently occurring errors in JavaScript. This error occurs when you attempt to read a property or call a function on an undefined object. You can reproduce it very easily by running the following code in a Chrome Developer console:

Here’s the output:

The error “Uncaught TypeError: Cannot read properties of undefined” is shown on a red background beside a red cross icon with func.call() above it.

An undefined object is one of the many possible causes of this error. Another prominent cause of this issue can be an improper initialization of the state while rendering the UI. Here’s a real-world example from a React application:

The app starts with an empty state container and is provided with some items after a delay of 2 seconds. The delay is put in place to imitate a network call. Even if your network is super fast, you’ll still face a minor delay due to which the component will render at least once. If you try to run this app, you’ll receive the following error:

The error “undefined is not an object” is shown on a grey background.

This is because, at the time of rendering, the state container is undefined; thus, there exists no property items on it. Fixing this error is easy. You just need to provide an initial default value to the state container.

Now, after the set delay, your app will show a similar output:

A bulleted list with two items reading

The exact fix in your code might be different, but the essence here is to always initialize your variables properly before using them.

4. TypeError: ‘undefined’ is not an object

This error occurs in Safari when you try to access the properties of or call a method on an undefined object. You can run the same code from above to reproduce the error yourself.

The error “TypeError: undefined is not an object” shown on a red background beside a red exclamation point icon with func.call() method call above it.

The solution to this error is also the same — make sure that you have initialized your variables correctly and they are not undefined when a property or method is accessed.

5. TypeError: null is not an object

This is, again, similar to the previous error. It occurs on Safari, and the only difference between the two errors is that this one is thrown when the object whose property or method is being accessed is null instead of undefined . You can reproduce this by running the following piece of code:

The

Since null is a value explicitly set to a variable and not assigned automatically by JavaScript. This error can occur only if you’re trying to access a variable you set null by yourself. So, you need to revisit your code and check if the logic that you wrote is correct or not.

6. TypeError: Cannot read property ‘length’

This error occurs in Chrome when you try to read the length of a null or undefined object. The cause of this issue is similar to the previous issues, but it occurs quite frequently while handling lists; hence it deserves a special mention. Here’s how you can reproduce the problem:

The error “Uncaught TypeError: Cannot read property 'length' of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

However, in the newer versions of Chrome, this error is reported as Uncaught TypeError: Cannot read properties of undefined . This is how it looks now:

The error “Uncaught TypeError: Cannot read properties of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

The fix, again, is to ensure that the object whose length you’re trying to access exists and is not set to null .

7. TypeError: ‘undefined’ is not a function

This error occurs when you try to invoke a method that doesn’t exist in your script, or it does but can not be referenced in the calling context. This error usually occurs in Google Chrome, and you can solve it by checking the line of code throwing the error. If you find a typo, fix it and check if it solves your issue.

If you have used the self-referencing keyword this in your code, this error might arise if this is not appropriately bound to your context. Consider the following code:

If you execute the above code, it will throw the error we discussed. It happens because the anonymous function passed as the event listener is being executed in the context of the document .

In contrast, the function showAlert is defined in the context of the window .

To solve this, you must pass the proper reference to the function by binding it with the bind() method:

8. ReferenceError: event is not defined

This error occurs when you try to access a reference not defined in the calling scope. This usually happens when handling events since they often provide you with a reference called event in the callback function. This error can occur if you forget to define the event argument in your function’s parameters or misspell it.

This error might not occur in Internet Explorer or Google Chrome (as IE offers a global event variable and Chrome attaches the event variable automatically to the handler), but it can occur in Firefox. So it’s advisable to keep an eye out for such small mistakes.

9. TypeError: Assignment to constant variable

This is an error that arises out of carelessness. If you try to assign a new value to a constant variable, you’ll be met with such a result:

The error “Uncaught TypeError: Assignment to constant variable” shown on a red background beside a red cross icon with func = 6 assignment above it.

While it seems easy to fix right now, imagine hundreds of such variable declarations and one of them mistakenly defined as const instead of let !  Unlike other scripting languages like PHP , there’s minimal difference between the style of declaring constants and variables in JavaScript. Therefore it’s advisable to check your declarations first of all when you face this error. You could also run into this error if you forget that the said reference is a constant and use it as a variable. This indicates either carelessness or a flaw in your app’s logic. Make sure to check this when trying to fix this issue.

10. (unknown): Script error

A script error occurs when a third-party script sends an error to your browser. This error is followed by (unknown) because the third-party script belongs to a different domain than your app. The browser hides other details to prevent leaking sensitive information from the third-party script.

You can not resolve this error without knowing the complete details. Here’s what you can do to get more information about the error:

  • Add the crossorigin attribute in the script tag.
  • Set the correct Access-Control-Allow-Origin header on the server hosting the script.
  • [Optional] If you don’t have access to the server hosting the script, you can consider using a proxy to relay your request to the server and back to the client with the correct headers.

Once you can access the details of the error, you can then set down to fix the issue, which will probably be with either the third-party library or the network.

How to Identify and Prevent Errors in JavaScript

While the errors discussed above are the most common and frequent in JavaScript, you’ll come across, relying on a few examples can never be enough. It’s vital to understand how to detect and prevent any type of error in a JavaScript application while developing it. Here is how you can handle errors in JavaScript.

Manually Throw and Catch Errors

The most fundamental way of handling errors that have been thrown either manually or by the runtime is to catch them. Like most other languages, JavaScript offers a set of keywords to handle errors. It’s essential to know each of them in-depth before you set down to handle errors in your JavaScript app.

The first and most basic keyword of the set is throw . As evident, the throw keyword is used to throw errors to create exceptions in the JavaScript runtime manually. We have already discussed this earlier in the piece, and here’s the gist of this keyword’s significance:

  • You can throw anything, including numbers, strings, and Error objects.
  • However, it’s not advisable to throw primitive data types such as strings and numbers since they don’t carry debug information about the errors.
  • Example: throw TypeError("Please provide a string")

The try keyword is used to indicate that a block of code might throw an exception. Its syntax is:

It’s important to note that a catch block must always follow the try block to handle errors effectively.

The catch keyword is used to create a catch block. This block of code is responsible for handling the errors that the trailing try block catches. Here is its syntax:

And this is how you implement the try and the catch blocks together:

Unlike C++ or Java, you can not append multiple catch blocks to a try block in JavaScript. This means that you can not do this:

Instead, you can use an if...else statement or a switch case statement inside the single catch block to handle all possible error cases. It would look like this:

The finally keyword is used to define a code block that is run after an error has been handled. This block is executed after the try and the catch blocks.

Also, the finally block will be executed regardless of the result of the other two blocks. This means that even if the catch block cannot handle the error entirely or an error is thrown in the catch block, the interpreter will execute the code in the finally block before the program crashes.

To be considered valid, the try block in JavaScript needs to be followed by either a catch or a finally block. Without any of those, the interpreter will raise a SyntaxError. Therefore, make sure to follow your try blocks with at least either of them when handling errors.

Handle Errors Globally With the onerror() Method

The onerror() method is available to all HTML elements for handling any errors that may occur with them. For instance, if an img tag cannot find the image whose URL is specified, it fires its onerror method to allow the user to handle the error.

Typically, you would provide another image URL in the onerror call for the img tag to fall back to. This is how you can do that via JavaScript:

However, you can use this feature to create a global error handling mechanism for your app. Here’s how you can do it:

With this event handler, you can get rid of the multiple try...catch blocks lying around in your code and centralize your app’s error handling similar to event handling. You can attach multiple error handlers to the window to maintain the Single Responsibility Principle from the SOLID design principles. The interpreter will cycle through all handlers until it reaches the appropriate one.

Pass Errors via Callbacks

While simple and linear functions allow error handling to remain simple, callbacks can complicate the affair.

Consider the following piece of code:

The above function demonstrates an asynchronous condition in which a function takes some time to process operations and returns the result later with the help of a callback.

If you try to enter a string instead of 4 in the function call, you’ll get NaN as a result.

This needs to be handled properly. Here’s how:

This should solve the problem ideally. However, if you try passing a string to the function call, you’ll receive this:

The error “Uncaught Error: Numeric argument is expected” shown on a dark red background beside a red cross icon.

Even though you have implemented a try-catch block while calling the function, it still says the error is uncaught. The error is thrown after the catch block has been executed due to the timeout delay.

This can occur quickly in network calls, where unexpected delays creep in. You need to cover such cases while developing your app.

Here’s how you can handle errors properly in callbacks:

Now, the output at the console will be:

The message “TypeError: Numeric argument is expected” shown on a dark grey background.

This indicates that the error has been appropriately handled.

Handle Errors in Promises

Most people tend to prefer promises for handling asynchronous activities. Promises have another advantage — a rejected promise doesn’t terminate your script. However, you still need to implement a catch block to handle errors in promises. To understand this better, let’s rewrite the calculateCube() function using Promises:

The timeout from the previous code has been isolated into the delay function for understanding. If you try to enter a string instead of 4, the output that you get will be similar to this:

The error “Uncaught (in promise) Error: Numeric argument is expected” shown on a dark grey background beside a red cross icon.

Again, this is due to the Promise throwing the error after everything else has completed execution. The solution to this issue is simple. Simply add a catch() call to the promise chain like this:

Now the output will be:

The message “Error: Numeric argument is expected” shown on a dark grey background.

You can observe how easy it is to handle errors with promises. Additionally, you can chain a finally() block and the promise call to add code that will run after error handling has been completed.

Alternatively, you can also handle errors in promises using the traditional try-catch-finally technique. Here’s how your promise call would look like in that case:

However, this works inside an asynchronous function only. Therefore the most preferred way to handle errors in promises is to chain catch and finally to the promise call.

throw/catch vs onerror() vs Callbacks vs Promises: Which is the Best?

With four methods at your disposal, you must know how to choose the most appropriate in any given use case. Here’s how you can decide for yourselves:

throw/catch

You will be using this method most of the time. Make sure to implement conditions for all possible errors inside your catch block, and remember to include a finally block if you need to run some memory clean-up routines after the try block.

However, too many try/catch blocks can make your code difficult to maintain. If you find yourself in such a situation, you might want to handle errors via the global handler or the promise method.

When deciding between asynchronous try/catch blocks and promise’s catch() , it’s advisable to go with the async try/catch blocks since they will make your code linear and easy to debug.

It’s best to use the onerror() method when you know that your app has to handle many errors, and they can be well-scattered throughout the codebase. The onerror method enables you to handle errors as if they were just another event handled by your application. You can define multiple error handlers and attach them to your app’s window on the initial rendering.

However, you must also remember that the onerror() method can be unnecessarily challenging to set up in smaller projects with a lesser scope of error. If you’re sure that your app will not throw too many errors, the traditional throw/catch method will work best for you.

Callbacks and Promises

Error handling in callbacks and promises differs due to their code design and structure. However, if you choose between these two before you have written your code, it would be best to go with promises.

This is because promises have an inbuilt construct for chaining a catch() and a finally() block to handle errors easily. This method is easier and cleaner than defining additional arguments/reusing existing arguments to handle errors.

Keep Track of Changes With Git Repositories

Many errors often arise due to manual mistakes in the codebase. While developing or debugging your code, you might end up making unnecessary changes that may cause new errors to appear in your codebase. Automated testing is a great way to keep your code in check after every change. However, it can only tell you if something’s wrong. If you don’t take frequent backups of your code, you’ll end up wasting time trying to fix a function or a script that was working just fine before.

This is where git plays its role. With a proper commit strategy, you can use your git history as a backup system to view your code as it evolved through the development. You can easily browse through your older commits and find out the version of the function working fine before but throwing errors after an unrelated change.

You can then restore the old code or compare the two versions to determine what went wrong. Modern web development tools like  GitHub Desktop or GitKraken help you to visualize these changes side by side and figure out the mistakes quickly.

A habit that can help you make fewer errors is running  code reviews whenever you make a significant change to your code. If you’re working in a team, you can create a pull request and have a team member review it thoroughly. This will help you use a second pair of eyes to spot out any errors that might have slipped by you.

Best Practices for Handling Errors in JavaScript

The above-mentioned methods are adequate to help you design a robust error handling approach for your next JavaScript application. However, it would be best to keep a few things in mind while implementing them to get the best out of your error-proofing. Here are some tips to help you.

1. Use Custom Errors When Handling Operational Exceptions

We introduced custom errors early in this guide to give you an idea of how to customize the error handling to your application’s unique case. It’s advisable to use custom errors wherever possible instead of the generic Error class as it provides more contextual information to the calling environment about the error.

On top of that, custom errors allow you to moderate how an error is displayed to the calling environment. This means that you can choose to hide specific details or display additional information about the error as and when you wish.

You can go so far as to format the error contents according to your needs. This gives you better control over how the error is interpreted and handled.

2. Do Not Swallow Any Exceptions

Even the most senior developers often make a rookie mistake — consuming exceptions levels deep down in their code.

You might come across situations where you have a piece of code that is optional to run. If it works, great; if it doesn’t, you don’t need to do anything about it.

In these cases, it’s often tempting to put this code in a try block and attach an empty catch block to it. However, by doing this, you’ll leave that piece of code open to causing any kind of error and getting away with it. This can become dangerous if you have a large codebase and many instances of such poor error management constructs.

The best way to handle exceptions is to determine a level on which all of them will be dealt and raise them until there. This level can be a controller (in an MVC architecture app) or a middleware (in a traditional server-oriented app).

This way, you’ll get to know where you can find all the errors occurring in your app and choose how to resolve them, even if it means not doing anything about them.

3. Use a Centralized Strategy for Logs and Error Alerts

Logging an error is often an integral part of handling it. Those who fail to develop a centralized strategy for logging errors may miss out on valuable information about their app’s usage.

An app’s event logs can help you figure out crucial data about errors and help to debug them quickly. If you have proper alerting mechanisms set up in your app, you can know when an error occurs in your app before it reaches a large section of your user base.

It’s advisable to use a pre-built logger or create one to suit your needs. You can configure this logger to handle errors based on their levels (warning, debug, info, etc.), and some loggers even go so far as to send logs to remote logging servers immediately. This way, you can watch how your application’s logic performs with active users.

4. Notify Users About Errors Appropriately

Another good point to keep in mind while defining your error handling strategy is to keep the user in mind.

All errors that interfere with the normal functioning of your app must present a visible alert to the user to notify them that something went wrong so the user can try to work out a solution. If you know a quick fix for the error, such as retrying an operation or logging out and logging back in, make sure to mention it in the alert to help fix the user experience in real-time.

In the case of errors that don’t cause any interference with the everyday user experience, you can consider suppressing the alert and logging the error to a remote server for resolving later.

5. Implement a Middleware (Node.js)

The  Node.js environment supports middlewares to add functionalities to server applications. You can use this feature to create an error-handling middleware for your server.

The most significant benefit of using middleware is that all of your errors are handled centrally in one place. You can choose to enable/disable this setup for testing purposes easily.

Here’s how you can create a basic middleware:

You can then use this middleware in your app like this:

You can now define custom logic inside the middleware to handle errors appropriately. You don’t need to worry about implementing individual error handling constructs throughout your codebase anymore.

6. Restart Your App To Handle Programmer Errors (Node.js)

When Node.js apps encounter programmer errors, they might not necessarily throw an exception and try to close the app. Such errors can include issues arising from programmer mistakes, like high CPU consumption, memory bloating, or memory leaks. The best way to handle these is to gracefully restart the app by crashing it via the Node.js cluster mode or a unique tool like PM2. This can ensure that the app doesn’t crash upon user action, presenting a terrible user experience.

7. Catch All Uncaught Exceptions (Node.js)

You can never be sure that you have covered every possible error that can occur in your app. Therefore, it’s essential to implement a fallback strategy to catch all uncaught exceptions from your app.

Here’s how you can do that:

You can also identify if the error that occurred is a standard exception or a custom operational error. Based on the result, you can exit the process and restart it to avoid unexpected behavior.

8. Catch All Unhandled Promise Rejections (Node.js)

Similar to how you can never cover for all possible exceptions, there’s a high chance that you might miss out on handling all possible promise rejections. However, unlike exceptions, promise rejections don’t throw errors.

So, an important promise that was rejected might slip by as a warning and leave your app open to the possibility of running into unexpected behavior. Therefore, it’s crucial to implement a fallback mechanism for handling promise rejection.

Like any other programming language, errors are quite frequent and natural in JavaScript. In some cases, you might even need to throw errors intentionally to indicate the correct response to your users. Hence, understanding their anatomy and types is very crucial.

Moreover, you need to be equipped with the right tools and techniques to identify and prevent errors from taking down your application.

In most cases, a solid strategy to handle errors with careful execution is enough for all types of JavaScript applications.

Are there any other JavaScript errors that you still haven’t been able to resolve? Any techniques for handling JS errors constructively? Let us know in the comments below!

typeerror assignment to constant

Kumar is a software developer and a technical author based in India. He specializes in JavaScript and DevOps. You can learn more about his work on his website .

Related Articles and Topics

typeerror assignment to constant

Powerful Managed WordPress Hosting

typeerror assignment to constant

The Ultimate Guide to Fixing and Troubleshooting the Most Common WordPress Errors (70+ Issues)

  • Website Security
  • Local Development

Leave a Reply Cancel reply

By submitting this form: You agree to the processing of the submitted personal data in accordance with Kinsta's Privacy Policy , including the transfer of data to the United States.

You also agree to receive information from Kinsta related to our services, events, and promotions. You may unsubscribe at any time by following the instructions in the communications received.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Uncaught (in promise) TypeError: Assignment to constant variable in JavaScript File [duplicate]

Im attempting to load a TensorFlow model into a javascript file and I'm getting an uncaught TypeError from a line but cant understand why I'm getting that error.

this is the block of code from which the error comes

and this was the console error message - letsscan1.js:12 Uncaught (in promise) TypeError: Assignment to constant variable. at letsscan1.js:12

Yeezus123's user avatar

  • Either you need to make MODEL_FILE_URL not const , or you shouldn't assign loadedModel to it. Does model.then return a new URL ? Doesn't really sound like it, but who knows… If it doesn't return a URL , you probably shouldn't assign it to a variable called "URL". –  deceze ♦ Mar 22, 2021 at 12:56

const type variables are of final type. Once this variable is assigned a value, its value cannot be changed.

You are overriding it here.

Omkar Kulkarni's user avatar

Not the answer you're looking for? Browse other questions tagged javascript tensorflow or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • An application of the (100/e)% rule applied to postdocs: moving on from an academic career, perhaps
  • Why did Kenny go to Heaven?
  • Is it correct to say: My friend can play more instruments than my A's at school?
  • A short story in French about furniture that leaves a mansion by itself, and comes back some time later
  • Bernoulli principle (classic form) in irrotational viscous flow (a paradox?)
  • Why are ETFs so bad at tracking Japanese indices?
  • Expected Amp difference going from SEU-AL to Copper on HVAC?
  • Word for a country declaring independence from an empire
  • When will the exclusive Pokemon Go Fest raids be released globally?
  • Parody of early D&D rules set, and specifically character creation, as part of a web novel of some kind
  • Is it possible to convert a Bézier curve to a NURBS curve while preserving the curve?
  • How much of an advantage is it to have high acceleration in space combat
  • Should I ask for authorship or ignore?
  • Why do I get different results for the products of two identical expressions?
  • Can someone explain the damage distrubution on this aircraft that flew through a hailstorm?
  • can you roll your own .iso for USB stick?
  • How should I join sections of concrete sidewalk poured in stages?
  • Ubuntu Terminal with alternating colours for each line
  • Group with a translation invariant ultrafilter
  • Find characters common among all strings
  • Why is array access not an infix operator?
  • Problems with coloured tables with \multirow and \multicolumn and text-wrapping for table with a lot of text. Getting blank, white areas
  • My players think they found a loophole that gives them infinite poison and XP. How can I add the proper challenges to slow them down?
  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?

typeerror assignment to constant

IMAGES

  1. Typeerror assignment to constant variable [SOLVED]

    typeerror assignment to constant

  2. TypeError: Assignment to Constant Variable in JavaScript

    typeerror assignment to constant

  3. TypeError: Assignment to Constant Variable in JavaScript

    typeerror assignment to constant

  4. TypeError: Assignment to Constant Variable in JavaScript

    typeerror assignment to constant

  5. TypeError: Assignment to constant variable-CSDN博客

    typeerror assignment to constant

  6. JavaScript

    typeerror assignment to constant

VIDEO

  1. 18- Constant in Python

  2. TypeError: Cannot redefine property: googletag

  3. TypeError WebDriver.__init__() got multiple values for argument 'options'

  4. JavaScript

  5. TypeError: not all arguments converted during string formatting

  6. Solution of 'Evaluation failed TypeError Cannot read properties of undefined reading whatsappwebjs

COMMENTS

  1. TypeError: invalid assignment to const "x"

    For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: js. const obj = { foo: "bar" }; obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'. But you can mutate the properties in a variable:

  2. TypeError: Assignment to constant variable

    Remember, const is appropriate for values that remain constant during execution, while let is more suitable for mutable variables. as an example I am giving an code. const pi = 3.14; // This variable cannot be reassigned a new value // To fix the error, use 'let' if you need to change the value let counter = 0; counter = 1; // This is valid ...

  3. TypeError: Assignment to Constant Variable in JavaScript

    To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const. Variables declared using the let keyword can be reassigned. We used the let keyword to declare the variable in the example. Variables declared using let can be reassigned, as opposed to variables declared using const.

  4. node.js

    Assignment to constant variable. Ask Question Asked 5 years, 6 months ago. Modified 1 month ago. Viewed 95k times 11 I try to read the user input and send it as a email. But when I run this code it gives me this error: Assignment to constant variable. var mail= require ...

  5. TypeError: invalid assignment to const "x"

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

  6. JavaScript const Keyword Explained with Examples

    The const keyword is used to declare a variable that can't be changed after its declaration. This keyword is short for constant (which means "doesn't change"), and it's used in a similar manner to the let and var keywords. You write the keyword, followed it up with a variable name, the assignment = operator, and the variable's value ...

  7. JavaScript Error: Assignment to Constant Variable

    In JavaScript, const is used to declare variables that are meant to remain constant and cannot be reassigned. Therefore, if you try to assign a new value to a constant variable, such as: 1 const myConstant = 10; 2 myConstant = 20; // Error: Assignment to constant variable 3. The above code will throw a "TypeError: Assignment to constant ...

  8. JavaScript TypeError

    This JavaScript exception is not a constructor that occurs if the code tries to use an object or a variable as a constructor, which is not a constructor. Message: TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not

  9. How to Fix Assignment to Constant Variable

    1 const pi = 3.14159; 2 pi = 3.14; // This will result in a TypeError: Assignment to constant variable 3 In the above example, we try to assign a new value to the pi variable, which was declared as a constant.

  10. Typeerror assignment to constant variable [SOLVED]

    TypeError: Assignment to constant variable. because we are trying to change the value of a constant variable.

  11. const

    const Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. Syntax const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]; nameN The constant's name, which can be any legal identifier. valueN The constant's value. This can be any legal expression, including a ...

  12. TypeError: invalid assignment to const "x"

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

  13. JavaScript Const

    emp = {id: 2, name: "Sachin"} //code1.js:2 Uncaught TypeError: Assignment to constant variable. Const and object. You cannot assign new content to a const variable. But if the content is an object, then we can modify the object itself.

  14. NodeJS TypeError: Assignment to Constant Variable

    The "NodeJS TypeError: Assignment to Constant Variable" error, while common, is easily avoidable. By understanding JavaScript's variable declaration nuances and adopting coding practices that embrace immutability, developers can write more robust and maintainable Node.js applications.

  15. [Fixed] TypeError: Assignment to constant variable in JavaScript

    Problem : TypeError: Assignment to constant variable. TypeError: Assignment to constant variable in JavaScript occurs when we try to reassign value to const variable. If we have declared variable with const, it can't be reassigned. Let's see with the help of simple example. Typeerror:assignment to constant variable. 1.

  16. Uncaught TypeError: Assignment to constant variable

    6. Identifiers imported from other modules cannot be reassigned. To achieve something like this, you can have the other module export a function that changes it, eg: export let SNAKE_SPEED = 3; export const changeSnakeSpeed = newSpeed => SNAKE_SPEED = newSpeed; import { snakeBody, SNAKE_SPEED, changeSnakeSpeed } from "./snake.js";

  17. 关于"TypeError: Assignment to constant variable"的问题解决方案

    在项目开发过程中,在使用变量声明时,如果不注意,可能会造成类型错误比如:Uncaught (in promise) TypeError: Assignment to constant variable.未捕获的类型错误:赋值给常量变量。. 原因我们使用 const 定义了变量且存在初始值。. 后面又给这个变量赋值,所以报错了。. ES6 ...

  18. TypeError: invalid assignment to const "x"

    TypeError: invalid assignment to const "x". JavaScript の例外 "invalid assignment to const" は、定数を変更しようとしたときに発生します。. JavaScript の const で宣言すると、再代入や再宣言を行うことができません。.

  19. A Definitive Guide to Handling Errors in JavaScript

    Get all your applications, databases, and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes: Easy setup and management in the MyKinsta dashboard; 24/7 expert support

  20. type error = assignment to constant variable react.js

    import React, { useState } from 'react' export default function App() { const [todos , set_todos] = useState(['']) const [input , set_input] = useState('') const new ...

  21. Uncaught (in promise) TypeError: Assignment to constant variable in

    Either you need to make MODEL_FILE_URL not const, or you shouldn't assign loadedModel to it. Does model.then return a new URL? Doesn't really sound like it, but who knows… If it doesn't return a URL, you probably shouldn't assign it to a variable called "URL". -

  22. null

    The value null is written with a literal: null . null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant. js.