TypeError: Assignment to Constant Variable in JavaScript

avatar

Last updated: Mar 2, 2024 Reading time · 3 min

banner

# TypeError: Assignment to Constant Variable in JavaScript

The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword.

When a variable is declared using const , it cannot be reassigned or redeclared.

assignment to constant variable

Here is an example of how the error occurs.

type error assignment to constant variable

# Declare the variable using let instead of const

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 .

You can also use the var keyword in a similar way. However, using var in newer projects is discouraged.

# Pick a different name for the variable

Alternatively, you can declare a new variable using the const keyword and use a different name.

pick different name for the variable

We declared a variable with a different name to resolve the issue.

The two variables no longer clash, so the "assignment to constant" variable error is no longer raised.

# Declaring a const variable with the same name in a different scope

You can also declare a const variable with the same name in a different scope, e.g. in a function or an if block.

declaring const variable with the same name in different scope

The if statement and the function have different scopes, so we can declare a variable with the same name in all 3 scopes.

However, this prevents us from accessing the variable from the outer scope.

# The const keyword doesn't make objects immutable

Note that the const keyword prevents us from reassigning or redeclaring a variable, but it doesn't make objects or arrays immutable.

const keyword does not make objects immutable

We declared an obj variable using the const keyword. The variable stores an object.

Notice that we are able to directly change the value of the name property even though the variable was declared using const .

The behavior is the same when working with arrays.

Even though we declared the arr variable using the const keyword, we are able to directly change the values of the array elements.

The const keyword prevents us from reassigning the variable, but it doesn't make objects and arrays immutable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: Unterminated string constant in JavaScript
  • TypeError (intermediate value)(...) is not a function in JS

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Troubleshooting and Fixing TypeError – Assignment to Constant Variable Explained

Introduction.

TypeError is a common error in JavaScript that occurs when a value is not of the expected type. One specific type of TypeError that developers often encounter is the “Assignment to Constant Variable” error. In this blog post, we will explore what a TypeError is and dive deep into understanding the causes of the “Assignment to Constant Variable” TypeError.

caught (in promise) typeerror assignment to constant variable

Causes of TypeError: Assignment to Constant Variable

The “Assignment to Constant Variable” TypeError is triggered when a developer attempts to modify a value assigned to a constant variable. There are a few common reasons why this error might occur:

Declaring a constant variable using the const keyword

One of the main causes of the “Assignment to Constant Variable” TypeError is when a variable is declared using the const keyword. In JavaScript, the const keyword is used to declare a variable that cannot be reassigned a new value. If an attempt is made to assign a new value to a constant variable, a TypeError will be thrown.

Attempting to reassign a value to a constant variable

Another cause of the “Assignment to Constant Variable” TypeError is when a developer tries to reassign a new value to a variable declared with the const keyword. Since constant variables are by definition, well, constant, trying to change their value will result in a TypeError.

Scoping issues with constant variables

Scoping plays an important role in JavaScript, and it can also contribute to the “Assignment to Constant Variable” TypeError. If a constant variable is declared within a specific scope (e.g., inside a block), any attempts to modify its value outside of that scope will throw a TypeError.

Common Scenarios and Examples

Scenario 1: declaring a constant variable and reassigning a value.

In this scenario, let’s consider a situation where a constant variable is declared, and an attempt is made to reassign a new value to it:

Explanation of the error:

When the above code is executed, a TypeError will be thrown, indicating that the assignment to the constant variable myVariable is not allowed.

Code example:

Troubleshooting steps:

  • Double-check the declaration of the variable to ensure that it is indeed declared using const . If it is declared with let or var , reassigning a value is allowed.
  • If you need to reassign a value to the variable, consider declaring it with let instead of const .

Scenario 2: Modifying a constant variable within a block scope

In this scenario, let’s consider a situation where a constant variable is declared within a block scope, and an attempt is made to modify its value outside of that block:

The above code will produce a TypeError, indicating that myVariable cannot be reassigned outside of the block scope where it is declared.

  • Ensure that you are referencing the constant variable within the correct scope. Trying to modify it outside of that scope will result in a TypeError.
  • If you need to access the variable outside of the block, consider declaring it outside the block scope.

Best Practices for Avoiding TypeError: Assignment to Constant Variable

Understanding when to use const vs. let.

In order to avoid the “Assignment to Constant Variable” TypeError, it’s crucial to understand the difference between using const and let to declare variables. The const keyword should be used when you know that the value of the variable will not change. If you anticipate that the value may change, consider using let instead.

Properly scoping constant variables

It’s essential to also pay attention to scoping when working with constant variables. Make sure that you are declaring the variables in the appropriate scope and avoid trying to modify them outside of that scope. This will help prevent the occurrence of the “Assignment to Constant Variable” TypeError.

Considerations for handling immutability

Immutability is a concept that is closely related to constant variables. Sometimes, using const alone may not be enough to enforce immutability. In such cases, you may need to use techniques like object freezing or immutable data structures to ensure that values cannot be modified.

In conclusion, the “Assignment to Constant Variable” TypeError is thrown when there is an attempt to modify a value assigned to a constant variable. By understanding the causes of this error and following best practices such as using const and let appropriately, scoping variables correctly, and considering immutability, you can write code that avoids this TypeError. Remember to pay attention to the specific error messages provided, as they can guide you towards the source of the problem and help you troubleshoot effectively.

By keeping these best practices in mind and understanding how to handle constant variables correctly, you can write cleaner and more reliable JavaScript code.

Related posts:

  • Mastering Assignment to Constant Variable – Understanding the Syntax and Best Practices
  • JavaScript Variable Types – Exploring the Differences Between var, let, and const
  • Understanding the Differences – const vs let vs var – Which One to Use?
  • Understanding Constant Variables in Java – A Complete Guide
  • Understanding Assignment to Constant Variable – Tips and Strategies for Effective Programming

‘let’ me be a ‘const’(ant), not a ‘var’(iable)!

‘let’ me be a ‘const’(ant), not a ‘var’(iable)!

by Srishti Gupta

var , let and const are the keywords which are used to declare variables in JavaScript. var comes under the ECMAScript 5th edition (aka ES5) whereas let and const fall under the category of ECMAScript 6th edition (aka ES6 and ES2015).

Since JavaScript does not have any type-checking, either of these keywords can be used to declare a variable of any type (datatype) in JavaScript.

Though all the three keywords are used for the same purpose, they are different.

‘let’ vs. ‘const’:

Change of value in future.

Variables declared using the let keyword can change their values in the future.

Consider the example given below:

On the first line, the variable iChange is declared using the let keyword and is initialized with value 11. When you come down to the next line, the variable iChange is again assigned a new value, which is 12. Changing the values of variables declared using the let keyword is allowed. When, on the last line, you try to print the value of the variable iChange , you correctly get the updated value 12.

Variables declared using the const keyword cannot change their values in future. This is why you must always initialize the variables declared with the const keyword.

Here, the variable PI is declared using the const keyword and is initialized with value 3.14 on the first line. When you come down to the next line, the variable PI is updated with a new value 22/7 . Changing values of variables declared using the const keyword is not allowed. This is why the second line throws the error shown in the output because you are trying to assign a new value to a constant variable. Therefore, remember that variables declared using the const keyword are read-only & cannot be reassigned any value.

As mentioned earlier, it is mandatory to initialize a constant when declaring it. Let’s see the following statement of code:

You know that you cannot update a constant in future. If you do not initialize a constant during its declaration, you will not be able to assign any value to it EVER! This is why you get a SyntaxError when you leave a constant uninitialized.

What do you think will be the output of the code given below?

Do you think an error will be thrown? Let’s check the output. Here we go.

The objects (including arrays & functions) declared using the const keyword are mutable.

So far, you’ve learned that variables declared using the const keyword cannot be assigned any other value. While this is true, there’s another side of the story too. Undoubtedly, you cannot assign a new value to a constant but you can manipulate the existing value if it is an object or an array.

In the code given above, you are not changing the entire value assigned to the constant passengerBus but you are manipulating a property inside it. You can add/delete/update a property inside an object declared using the const keyword.

Similar can be done with arrays too. You can add add/delete/update an element inside an array declared using a const keyword.

Now, considering that the keywords let and const belong to the same category, the following points enlist the differences between the variables declared using the let / const keywords and the variables declared using the var keyword:

‘let’ (or ‘const’) vs. ‘var’:

Variables declared using the let / const keywords are block-scoped .

Consider the following example:

The variable i is declared using the let keyword inside the for-loop block. This means that when the for-loop block ends, the variable i loses its scope and is no longer accessible outside the curly braces of the for-loop block. Thus, when you try to access the variable i and print its value on statement 2, you get a ReferenceError: i is not defined , as shown in the output.

Consider another example of declaring a variable using the const keyword:

The variable message is declared using the const keyword inside the if-block. This means that when the if-block ends, the variable message loses its scope and is no longer accessible outside the curly braces of the if-block. This is why, when you try to access variable message and print its value on statement 2, you get a ReferenceError: message is not defined , as shown in the output.

Variables declared using the var keyword are function-scoped .

Consider the example which we’ve discussed earlier where instead of using let , you use the var keyword to declare the variable i :

The variable i is declared using the var keyword inside the for-loop-block. Because the variables declared using the var keyword are function-scoped, the variable i does not go out of scope when the for-loop-block ends and is accessible anywhere inside the scope of the function foo . Thus, on statement 2, when you try to access the variable i and print its value, you get the correct output as 3 (incremented value of variable i after the for-loop’s increment statement is executed) as shown in the output.

Redeclaration

Variables declared using the let / const keywords cannot be redeclared in the same scope.

What do you think will be the output of the following code?

In the above code, you declared a variable with the name avengers using the let keyword and then you declared it again on the next line. Thus, the second line throws an SyntaxError as mentioned in the output.

Variables declared using the var keyword can be redeclared in the same scope.

Let’s now declare a variable already declared earlier in the same scope using the var keyword.

As evident from the output , you can redeclare variables having the same name in the same scope using the var keyword. The value contained in the variable will be the final value that you have assigned to it.

Variables declared using the let / const keywords are NOT hoisted .

This is an important point which is forgotten by many and you won’t find it in all articles. To understand what this point means, consider the example given below:

Notice that on the first line in the code given above, you are trying to access a variable x , which is declared and assigned a value on the next line. Essentially, you are trying to access a variable, which has not yet been allocated memory (declared). Since the variable x is declared using the let keyword and the variables declared using the let / const keywords are not hoisted, this throws a ReferenceError: x is not defined , as shown in the output.

Variables declared using the var keyword are hoisted to the top of their scope .

All the declarations are moved to the top of the scope. Notice that on the first line, you are trying to access a variable x , which is declared and assigned a value on the next line. Now, since the variable x is declared using the var keyword and the variables declared using the var keyword are hoisted to the top of their scope in JavaScript, the code gets converted to the one given below:

Here, the variable x is declared on line 1 and is not assigned any value. All the variables in JavaScript are initialized with the default value undefined , if no other value is assigned explicitly by the user. Thus, x is assigned the value undefined , which is what is printed on the second line (before x is updated to 10).

The Bigger Question — What to Prefer?

ES6 (aka ES2015) is supported by almost all the browsers today. If you can follow this syntax, it is recommended to use the let and const keywords for declaring all the variables in your code.

Now, which one to choose amongst let and const ? The title says it all.

rj5mGjbr0EVJzlpIYxLgMluer6heMLZSsG0i

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How to Fix the ‘TypeError: invalid assignment to const “x” ‘ Error in Our JavaScript App?

  • Post author By John Au-Yeung
  • Post date August 22, 2021
  • No Comments on How to Fix the ‘TypeError: invalid assignment to const “x” ‘ Error in Our JavaScript App?

caught (in promise) typeerror assignment to constant variable

Sometimes, we may run into the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps.

Fix the ‘TypeError: invalid assignment to const "x"’ When Developing JavaScript Apps

To fix the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps, we should make sure we aren’t assigning a variable declared with const to a new value.

On Firefox, the error message for this error is TypeError: invalid assignment to const "x" .

On Chrome, the error message for this error is TypeError: Assignment to constant variable.

And on Edge, the error message for this error is TypeError: Assignment to const .

For example, the following code will throw this error:

We tried to assign 100 to COLUMNS which is declared with const , so we’ll get this error.

To fix this, we write:

to declare 2 variables, or we can use let to declare a variable that we can reassign a value to:

Related Posts

Sometimes, we may run into the 'RangeError: invalid date' when we're developing JavaScript apps. In…

Sometimes, we may run into the 'TypeError: More arguments needed' when we're developing JavaScript apps.…

Sometimes, we may run into the 'TypeError: "x" has no properties' when we're developing JavaScript…

caught (in promise) typeerror assignment to constant variable

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

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.

caught (in promise) typeerror assignment to constant variable

Itsourcecode.com

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.

First, let us know what this error means.

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.

In JavaScript, when you declare a variable using the const keyword, its value cannot be changed or reassigned.

Attempting to modify a constant variable, you will receive an error stating:

Here is an example code snippet that triggers the error:

In this example, we have declared a constant variable greeting and assigned it the value “Hello” .

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.

Let us explore more about how this error occurs.

How does Typeerror assignment to constant variable occurs ?

This “ TypeError: Assignment to constant variable ” error occurs when you attempt to modify a variable that has been declared as a constant.

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

When you declare a variable using the const keyword, you are telling JavaScript that the value of the variable will remain constant throughout the program.

If you try to modify the value of a constant variable, you will get the error:

This error can occur in various situations, such as:

  • Attempting to reassign a constant variable:

When you declare a variable using the const keyword, its value cannot be changed.

If you try to reassign the value of a constant variable, you will get this error.

Here is an example :

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

When we try to reassign age to a different value ( 35 ), we will get the error:

  • Attempting to modify a constant object:

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

However, you cannot reassign the entire object to a new value.

If you try to reassign a constant object, you will get the error.

For example:

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

We are able to modify the age property of the object without triggering an error.

However, when we try to reassign person to a new object, we will get the Typeerror.

  • Using strict mode:

In strict mode, JavaScript throws more errors to help you write better code.

If you try to modify a constant variable in strict mode, you will get the error.

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

However, because we are using strict mode, any attempt to modify the value of name will trigger the error.

Now let’s fix this error.

Typeerror assignment to constant variable – Solutions

Here are the alternative solutions that you can use to fix “Typeerror assignment to constant variable” :

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:

If you are using strict mode and need to modify a variable, you can declare the variable outside of strict mode:

Solution 4: Use the const keyword and use a different name :

This allows you to keep the original constant variable intact and create a new variable with a different value.

Solution 5: Declare a const variable with the same name in a different scope :

This allows you to create a new constant variable with the same name as the original constant variable.

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

For Example:

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

By declaring a constant variable with the same name in a different scope.

This can be useful when you need to use the same variable name in multiple scopes without causing conflicts or errors.

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

By following those solutions, you can fix the “Typeerror assignment to constant variable” error in your JavaScript code.

Here are the other fixed errors that you can visit, you might encounter them in the future.

  • typeerror unsupported operand type s for str and int
  • typeerror: object of type int64 is not json serializable
  • typeerror: bad operand type for unary -: str

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

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding a  Typeerror   stating  “assignment to constant variable” .

We’re happy to help you.

Happy coding! Have a Good day and God bless.

caught (in promise) typeerror assignment to constant variable

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ether.js error: Assignment to constant variable #3010

@ricmoo

programmer-zhang commented May 23, 2022

@programmer-zhang

ricmoo commented May 26, 2022

Sorry, something went wrong.

@Bommer2078

Bommer2078 commented Jul 19, 2022

@xl-youcanknow

xl-youcanknow commented Jul 28, 2022

@heyuanlong

heyuanlong commented Sep 22, 2022

No branches or pull requests

@ricmoo

  • [email protected]
  • 🇮🇳 +91 (630)-411-6234
  • 🇺🇸 +1 (334) 517-0924
  • 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.

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

Browser compatibility.

  • Constants in the JavaScript Guide

© 2005–2021 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String . This chapter describes JavaScript regular expressions.

Creating a regular expression

You construct a regular expression in one of two ways:

  • Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: js const re = / ab + c / ; Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.
  • Or calling the constructor function of the RegExp object, as follows: js const re = new RegExp ( "ab+c" ) ; Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Writing a regular expression pattern

A regular expression pattern is composed of simple characters, such as /abc/ , or a combination of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/ . The last example includes parentheses, which are used as a memory device. The match made with this part of the pattern is remembered for later use, as described in Using groups .

Note: If you are already familiar with the forms of a regular expression, you may also read the cheat sheet for a quick lookup for a specific pattern/construct.

Using simple patterns

Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern /abc/ matches character combinations in strings only when the exact sequence "abc" occurs (all characters together and in that order). Such a match would succeed in the strings "Hi, do you know your abc's?" and "The latest airplane designs evolved from slabcraft." . In both cases the match is with the substring "abc" . There is no match in the string "Grab crab" because while it contains the substring "ab c" , it does not contain the exact substring "abc" .

Using special characters

When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern. For example, to match a single "a" followed by zero or more "b" s followed by "c" , you'd use the pattern /ab*c/ : the * after "b" means "0 or more occurrences of the preceding item." In the string "cbbabbbbcdebc" , this pattern will match the substring "abbbbc" .

The following pages provide lists of the different special characters that fit into each category, along with descriptions and examples.

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).

Distinguish different types of characters. For example, distinguishing between letters and digits.

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

Indicate numbers of characters or expressions to match.

If you want to look at all the special characters that can be used in regular expressions in a single table, see the following:

Note: A larger cheat sheet is also available (only aggregating parts of those individual articles).

If you need to use any of the special characters literally (actually searching for a "*" , for instance), you must escape it by putting a backslash in front of it. For instance, to search for "a" followed by "*" followed by "b" , you'd use /a\*b/ — the backslash "escapes" the "*" , making it literal instead of special.

Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern). For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use /\/example\/[a-z]+/i —the backslashes before each slash make them literal.

To match a literal backslash, you need to escape the backslash. For instance, to match the string "C:\" where "C" can be any letter, you'd use /[A-Z]:\\/ — the first backslash escapes the one after it, so the expression searches for a single literal backslash.

If using the RegExp constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level. /a\*b/ and new RegExp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" followed by "b".

If escape strings are not already part of your pattern you can add them using String.prototype.replace() :

The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches. It is explained in detail below in Advanced Searching With Flags .

Why isn't this built into JavaScript? There is a proposal to add such a function to RegExp.

Using parentheses

Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. Once remembered, the substring can be recalled for other use. See Groups and backreferences for more details.

Using regular expressions in JavaScript

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , matchAll() , replace() , replaceAll() , search() , and split() .

When you want to know whether a pattern is found in a string, use the test() or search() methods; for more information (but slower execution) use the exec() or match() methods. If you use exec() or match() and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, RegExp . If the match fails, the exec() method returns null (which coerces to false ).

In the following example, the script uses the exec() method to find a match in a string.

If you do not need to access the properties of the regular expression, an alternative way of creating myArray is with this script:

(See Using the global search flag with exec() for further info about the different behaviors.)

If you want to construct the regular expression from a string, yet another alternative is this script:

With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.

As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. If you do, however, every occurrence is a new regular expression. For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. For example, assume you have this script:

However, if you have this script:

The occurrences of /d(b+)d/g in the two statements are different regular expression objects and hence have different values for their lastIndex property. If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.

Advanced searching with flags

Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression.

To include a flag with the regular expression, use this syntax:

Note that the flags are an integral part of a regular expression. They cannot be added or removed later.

For example, re = /\w+\s/g creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.

You could replace the line:

and get the same result.

The m flag is used to specify that a multiline input string should be treated as multiple lines. If the m flag is used, ^ and $ match at the start or end of any line within the input string instead of the start or end of the entire string.

Using the global search flag with exec()

RegExp.prototype.exec() method with the g flag returns each match and its position iteratively.

In contrast, String.prototype.match() method returns all matches at once, but without their position.

Using unicode regular expressions

The u flag is used to create "unicode" regular expressions; that is, regular expressions which support matching against unicode text. An important feature that's enabled in unicode mode is Unicode property escapes . For example, the following regular expression might be used to match against an arbitrary unicode "word":

Unicode regular expressions have different execution behavior as well. RegExp.prototype.unicode contains more explanation about this.

Note: Several examples are also available in:

  • The reference pages for exec() , test() , match() , matchAll() , search() , replace() , split()
  • The guide articles: character classes , assertions , groups and backreferences , quantifiers

Using special characters to verify input

In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid.

The regular expression looks for:

  • the beginning of the line of data: ^
  • followed by three numeric characters \d{3} OR | a left parenthesis \( , followed by three digits \d{3} , followed by a close parenthesis \) , in a non-capturing group (?:)
  • followed by one dash, forward slash, or decimal point in a capturing group ()
  • followed by three digits \d{3}
  • followed by the match remembered in the (first) captured group \1
  • followed by four digits \d{4}
  • followed by the end of the line of data: $

An online tool to learn, build, & test Regular Expressions.

An online regex builder/debugger

An online interactive tutorials, Cheat sheet, & Playground.

An online visual regex tester.

IMAGES

  1. How to Fix Uncaught TypeError: Assignment to constant variable

    caught (in promise) typeerror assignment to constant variable

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

    caught (in promise) typeerror assignment to constant variable

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

    caught (in promise) typeerror assignment to constant variable

  4. Typeerror assignment to constant variable [SOLVED]

    caught (in promise) typeerror assignment to constant variable

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

    caught (in promise) typeerror assignment to constant variable

  6. TypeError: Assignment to Constant Variable in JavaScript

    caught (in promise) typeerror assignment to constant variable

VIDEO

  1. Uncaught TypeError : assignement to constant variable #javascript #js #uncaught #typeerror

  2. Caught in the Act: The Zuai Way!#zuai #shorts

COMMENTS

  1. node.js

    Assignment to constant variable. Ask Question Asked 5 years, 5 months ago. Modified 21 days 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 ...

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

  4. 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. The code for this article is available on GitHub. We used the let keyword to declare the variable in the example. Variables declared using let can be ...

  5. Troubleshooting and Fixing TypeError

    In order to avoid the "Assignment to Constant Variable" TypeError, it's crucial to understand the difference between using const and let to declare variables. The const keyword should be used when you know that the value of the variable will not change.

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

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

  8. 'let' me be a 'const'(ant), not a 'var'(iable)!

    Uncaught TypeError: Assignment to constant variable. Here, the variable PI is declared using the const keyword and is initialized with value 3.14 on the first line. When you come down to the next line, the variable PI is updated with a new value 22/7. Changing values of variables declared using the const keyword is not allowed. This is why the ...

  9. How to Fix the 'TypeError: invalid assignment to const "x" ' Error in

    to declare 2 variables, or we can use let to declare a variable that we can reassign a value to: let COLUMNS = 80; // ... COLUMNS = 100; Conclusion. To fix the 'TypeError: invalid assignment to const "x"' when we're developing JavaScript apps, we should make sure we aren't assigning a variable declared with const to a new value.

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

    文章浏览阅读4.5w次,点赞16次,收藏17次。. 在项目开发过程中,在使用变量声明时,如果不注意,可能会造成类型错误比如:Uncaught (in promise) TypeError: Assignment to constant variable.未捕获的类型错误:赋值给常量变量。. 原因我们使用 const 定义了变量且存在初始值 ...

  11. Typeerror assignment to constant variable [SOLVED]

    because we are trying to change the value of a constant variable. Attempting to modify a constant object: If you declare an object using the const keyword, you can still modify the properties of the object.

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

    Uncaught (in promise) TypeError: Assignment to constant variable. #2331. Closed DelingAlieZ10 opened this issue Nov 25, 2021 · 11 comments Closed ... Uncaught (in promise) TypeError: Assignment to constant variable. at index.js:210 at Array.forEach at new vn (index.js:545) at new gn (index.js:890) at Object. (ethers-util.js:160)

  13. TypeError: Assignment to constant variable. #16211

    TypeError: Assignment to constant variable. System: OSX npm: 6.10.2 node: v10.13. react: 16.8.6. The text was updated successfully, but these errors were encountered: All reactions. Copy link artuross commented Jul 26, 2019 • edited ...

  14. ether.js error: Assignment to constant variable #3010

    Uncaught (in promise) TypeError: Assignment to constant variable. at index.js:215:1 at Array.forEach (< anonymous >) at new gn (index.js:551:1) at ... TypeError: Assignment to constant variable. #2331. Closed Copy link Member. ricmoo commented May 26, 2022. I don't think this can be an issue necessarily with ethers; does Vue use some sort of ...

  15. 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. Remember, consistent coding standards and thorough ...

  16. Uncaught TypeError: Assignment to constant variable

    I take it that variable data is an object. It's illegal syntax to have '\' in a object property key unless you incapsule them in quotes. //Wrong var data = { game\_crash: 'sucker' } // Uncaught SyntaxError: Invalid or unexpected token //Correct var data = { "game\_crash": 'sucker' } // correct but bad naming convension.

  17. Uncaught TypeError: Assignment to constant variable

    r/reactjs • I'm in a group of devs who volunteer to build projects which benefit society in our spare time. We're just about to launch a homelessness, and a climate action platform but have a few React tasks left to complete.

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

  19. Error "Assignment to constant variable" in ReactJS

    Maybe what you are looking for is Object.assign(resObj, { whatyouwant: value} ). This way you do not reassign resObj reference (which cannot be reassigned since resObj is const), but just change its properties.. Reference at MDN website. Edit: moreover, instead of res.send(respObj) you should write res.send(resObj), it's just a typo

  20. Regular expressions

    TypeError: invalid assignment to const "x" TypeError: More arguments needed; TypeError: property "x" is non-configurable and can't be deleted; TypeError: Reduce of empty array with no initial value; TypeError: setting getter-only property "x" TypeError: X.prototype.y called on incompatible type; URIError: malformed URI sequence

  21. TypeError: Assignment to constant variable, when trying to create an

    What I see is that you assigned the variable apartments as an array and declared it as a constant. Then, you tried to reassign the variable to an object. When you assign the variable as a const array and try to change it to an object, you are actually changing the reference to the variable, which is not allowed using const.. const apartments = []; apartments = { link: getLink, descr ...