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

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

TypeError: invalid assignment to const "x"

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

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:

React Tutorial

React hooks, react exercises, react es6 variables.

Before ES6 there was only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined.

Now, with ES6, there are three ways of defining your variables: var , let , and const .

If you use var outside of a function, it belongs to the global scope.

If you use var inside of a function, it belongs to that function.

If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block.

var has a function scope, not a block scope.

let is the block scoped version of var , and is limited to the block (or expression) where it is defined.

If you use let inside of a block, i.e. a for loop, the variable is only available inside of that loop.

let has a block scope.

Get Certified!

const is a variable that once it has been created, its value can never change.

const has a block scope.

The keyword const is a bit misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Test Yourself With Exercises

Create a variable that cannot be changed.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

useState in React: A complete guide

assignment to constant variable react

Editor’s note: This React useState Hook tutorial was last updated on 7 February 2023 to include more information on React useState and to reflect updates to React. Check out our React Hooks reference guide and cheat sheet for more information about React Hooks.

useState in React: A Complete Guide

The React useState Hook allows you to have state variables in functional components. You pass the initial state to this function, and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

This tutorial serves as a complete guide to the useState Hook in React, the equivalent of this.state / this.setSate for functional components.

If you’re just getting started with React Hooks and looking for a visual guide, check out the video tutorial below:

Class and functional components in React

There are two types of components in React: class and functional components.

Class components are ES6 classes that extend the built-in Component class and can have state and lifecycle methods:

N.B. , the React team recommends defining components as functions instead of classes. Here’s a migration guide .

Functional components are functions that accept arguments as the properties of the component and return valid JSX, as shown below:

As you can see, there are no state or lifecycle methods. However, as of React v16.8, we can use Hooks. React Hooks are functions that add state variables to functional components and instrument the lifecycle methods of classes. They tend to start with use .

What is the useState Hook?

useState is React Hook that allows you to add state to a functional component . It returns an array with two values: the current state and a function to update it. The Hook takes an initial state value as an argument and returns an updated state value whenever the setter function is called. It can be used like this:

Here, the initialValue is the value you want to start with, and state is the current state value that can be used in your component. The setState function can be used to update the state , triggering a re-render of your component.

What can useState hold?

In React, useState can store any type of value, whereas the state in a class component is limited to being an object. This includes primitive data types like string , number , and Boolean , as well as complex data types such as array , object , and function . It can even cover custom data types like class instances.

Basically, anything that can be stored in a JavaScript variable can be stored in a state managed by useState .

Updating objects and arrays in useState

Never directly modify an object or array stored in useState . Instead, you should create a new updated version of the object or array and call setState with the new version. For example:

What does the React.useState Hook do?

As stated previously, useState enables you to add state to function components. Calling React.useState inside a function component generates a single piece of state associated with that component.

Whereas the state in a class is always an object, with Hooks, the state can be any type. Each piece of state holds a single value: an object , an array , a Boolean , or any other type you can imagine.

So, when should you use the useState Hook? Well, it’s beneficial for local component state, but larger projects can require additional state management solutions.

Declaring state in React

useState is a named export from react . To use it, you can write React.useState or import it by writing useState :

The state object that can be declared in a class and allows you to declare more than one state variable, as shown below:

However, unlike the state object, the useState Hook allows you to declare only one state variable (of any type) at a time, like this:

So, useState takes the initial value of the state variable as an argument, and you can pass it directly, as shown in the previous example. You can also use a function to lazily initialize the variable. This is useful when the initial state is the result of an expensive computation, as shown below:

The initial value will be assigned only on the initial render. If it’s a function, it will be executed only on the initial render. In subsequent renders (due to a change of state in the component or a parent component), the argument of the useState Hook will be ignored, and the current value will be retrieved.

It is important to keep this in mind because, for example, if you want to update the state based on the new properties the component receives, using useState alone won’t work. This is because its argument is used the first time only — not every time the property changes (look here for the right way to do this). This is shown here:

But, useState doesn’t return just a variable, as the previous examples imply. It returns an array, where the first element is the state variable and the second element is a function to update the value of the variable:

Usually, you’ll use array destructuring to simplify the code shown above like this:

This way, you can use the state variable in the functional component like any other variable:

But, why does useState return an array? This is because, compared to an object, an array is more flexible and easy to use. If the method returned an object with a fixed set of properties, you wouldn’t be able to assign custom names easily.

Instead, you’d have to do something like this (assuming the properties of the object are state and setState ):

Using React Hooks to update the state

The second element returned by useState is a function that takes a new value to update the state variable. Here’s an example that uses a text box to update the state variable on every change:

You can try that here:

However, this update function doesn’t update the value right away. Instead, it enqueues the update operation. Then, after re-rendering the component, the argument of useState will be ignored, and this function will return the most recent value.

When updating state based on its previous value, you need to pass a function to the setter function that updates the state. This function receives the previous state value as an argument and returns the new state value, as shown below:

Implementing an object as a state variable with useState Hook

There are two things you need to keep in mind about updates when using objects:

  • The importance of immutability
  • And the fact that the setter returned by useState doesn’t merge objects like setState() does in class components

About the first point, if you use the same value as the current state to update the state (React uses Object.is() for comparing), React won’t trigger a re-render.

When working with objects, it’s easy to make the following mistake :

Here’s the Code Sandbox:

Instead of creating a new object, the above example mutates the existing state object. To React, that’s the same object. To make it work, we must create a new object, just like we discussed earlier:

This leads us to the second important thing you need to remember. When you update a state variable, unlike this.setState in a class component, the function returned by useState does not automatically merge update objects, it replaces them.

Following the previous example, if we add another property to the message object ( id ) as shown below:

And we only update the message property like in the above example, React will replace the original { message: '', id: 1 } state object with the object used in the onChange event, which only contains the message property:

{ message: ‘message entered’ } // id property is lost

You can see how the id property is lost here:

You can replicate the behavior of setState() by using the function argument that contains the object to be replaced and the object spread syntax:

The ...prevState part will get all of the properties of the object, and the message: val part will overwrite the message property. This will have the same result as using Object.assign() (just remember to create a new object):

Try it here:

However, the spread syntax simplifies this operation, and it also works with arrays. Basically, when applied to an array, the spread syntax removes the brackets so you can create another one with the values of the original array:

Here’s an example that shows how to use useState with arrays:

You have to be careful when applying the spread syntax to multi-dimensional arrays because it won’t work as you might expect. This leads us to another thing to consider when working with objects as the state.

assignment to constant variable react

Over 200k developers use LogRocket to create better digital experiences

assignment to constant variable react

How to update state in a nested object in React with Hooks

In JavaScript, multi-dimensional arrays are arrays within arrays, as shown below:

You could use them to group all your state variables in one place. However, for that purpose, it would be better to use nested objects like this:

But, the problem when working with multi-dimensional arrays and nested objects is that Object.assign and the spread syntax will create a shallow copy instead of a deep copy .

From the spread syntax documentation :

Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multi-dimensional arrays, as the following example shows. (The same is true with Object.assign() and spread syntax.)

This Stack Overflow query offers good explanations for the above example, but the important point is that when using nested objects, we can’t just use the spread syntax to update the state object. For example, consider the following state object:

The following code snippets show some incorrect ways to update the text field:

To properly update the text field, we have to copy to a new object the entire set of fields/nested objects of the original object:

In the same way, here’s how you’d update the author field of the state object:

However, this is assuming the message object doesn’t change. If it does change, you’d have to update the object this way:

Working with multiple state variables or one state object

When working with multiple fields or values as the state of your application, you have the option of organizing the state using multiple state variables:

However, you have to be careful when using state objects with a complex structure (nested objects). Consider this example:

If you have to update a specific field nested deep in the object, you’ll have to copy all the other objects along with the key-value pairs of the object that contains that specific field:

In some cases, cloning deeply nested objects can be expensive because React may re-render parts of your applications that depend on fields that haven’t even changed.

For this reason, the first thing you need to consider is trying to flatten your state object(s). In particular, the React documentation recommends splitting the state into multiple state variables based on which values tend to change together.

If this is not possible, the recommendation is to use libraries that help you work with immutable objects, such as immutable.js or immer .

Rules for using useState

useState abides by the same rules that all Hooks follow :

  • Only call Hooks at the top level
  • Only call Hooks from React functions

The second rule is easy to follow. Don’t use useState in a class component:

Or regular JavaScript functions (not called inside a functional component):

You’ll get an error . The first rule means that even inside functional components, you shouldn’t call useState in loops, conditions, or nested functions because React relies on the order in which useState functions are called to get the correct value for a particular state variable.

In that regard, the most common mistake is to wrap useState calls in a conditional statement (they won’t be executed all the time):

A functional component can have many calls to useState or other Hooks. Each Hook is stored in a list, and there’s a variable that keeps track of the currently executed Hook.

When useState is executed, the state of the current Hook is read (or initialized during the first render), and then, the variable is changed to point to the next Hook. That’s why it is important to always maintain the Hook calls in the same order. Otherwise, a value belonging to another state variable could be returned.

In general terms, here’s an example of how this works step by step:

  • React initializes the list of Hooks and the variable that keeps track of the current Hook
  • React calls your component for the first time
  • React finds a call to useState , creates a new Hook object (with the initial state), changes the current Hook variable to point to this object, adds the object to the Hooks list, and returns the array with the initial state and the function to update it
  • React finds another call to useState and repeats the actions of the previous step, storing a new Hook object and changing the current Hook variable
  • The component state changes
  • React sends the state update operation (performed by the function returned by useState ) to a queue to be processed
  • React determines it needs to re-render the component
  • React resets the current Hook variable and calls your component
  • React finds a call to useState , but this time, since there’s already a Hook at the first position of the list of Hooks, it just changes the current Hook variable and returns the array with the current state, and the function to update it
  • React finds another call to useState and because a Hook exists in the second position, once again, it just changes the current Hook variable and returns the array with the current state and the function to update it

If you like to read code, refer to the ReactFiberHooks class to learn how Hooks work under the hood.

useState vs. useEffect

useState and useEffect are two of the most important Hooks in React. They allow you to manage state and side effects in your functional components. However, they serve different purposes and should be used in different ways.

As we discussed earlier, the useState is a Hook that allows you to add state to your functional component. It returns an array with two values: the current state and a setter function for updating the state.

useEffect is a Hook that is used to manage side effects in functional components. A side-effect is any operation that impacts the component outside of its render, such as making an API call or setting up a timer. For example, consider a component that fetches data from an API and displays it in a list:

In this example, the useEffect Hook is used to make an API call and update the data state whenever the component is rendered. The Hook takes a callback function as an argument, which will be executed after every render of the component. The second argument to useEffect is an array of dependencies, which determines when the effect should run. In this case, the empty array means that the effect will only run once when the component is mounted.

useState is used for managing state that needs to be updated and re-rendered based on user interactions or other events in the component. On the other hand, useEffect is used to manage side effects that need to run after every render of the component or perform any cleanup when the component unmounts. Understanding the differences between these Hooks allows you to make informed decisions about when to use each Hook and build robust and scalable React applications.

Understanding the useReducer Hook

For advanced use cases, you can use the useReducer Hook as an alternative to useState . This is especially useful when you have complex state logic that uses multiple sub-values or when a state depends on the previous one.

Here’s how to use the useReducer Hook:

useReducer returns an array that holds the current state value and a dispatch method. This should be familiar territory if you have experience using Redux. Whereas with useState , you invoke the state updater function to update state, with useReducer , you invoke the dispatch function and pass it an action. For example, an object with at least a type property, like this one:

Conventionally, an action object may also have a payload , for example, {action: 'increase', payload: 10} . While it’s not absolutely necessary to pass an action object that follows this pattern, it’s a very common pattern popularized by Redux .

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function, and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

Here are some important key points to remember:

  • The update function doesn’t update the value right away
  • If you use the previous value to update state, you must pass a function that receives the previous value and returns an updated value, for example, setMessage(previousVal => previousVal + currentVal)
  • If you use the same value as the current state to update the state, React won’t trigger a re-render
  • Unlike this.setState in class components, useState doesn’t merge objects when the state is updated. It replaces them
  • useState follows the same rules that all Hooks do. In particular, pay attention to the order in which these functions are called (there’s an ESLint plugin that will help you enforce these rules)

Get set up with LogRocket's modern React error tracking in minutes:

  • Visit https://logrocket.com/signup/ to get an app ID

Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Recent posts:

Rescript Vs Typescript Overview And Comparison

ReScript vs. TypeScript: Overview and comparison

Many modern web developers are embracing emerging technologies that improve the speed of development as well as the quality of […]

assignment to constant variable react

Using Pavex for Rust web development

The Pavex Rust web framework is an exciting project that provides high performance, great usability, and speed.

assignment to constant variable react

Using the ResizeObserver API in React for responsive designs

With ResizeObserver, you can build aesthetic React apps with responsive components that look and behave as you intend on any device.

assignment to constant variable react

Creating JavaScript tables using Tabulator

Explore React Tabulator to create interactive JavaScript tables, easily integrating pagination, search functionality, and bulk data submission.

assignment to constant variable react

15 Replies to "<code>useState</code> in React: A complete guide"

Thanks for a great article. By the way, I don’t think this part of the article true.

> If you use the same value as the current state (React uses the Object.is for comparing) to update the state, React won’t trigger a re-render

https://codesandbox.io/embed/react-hooks-playground-cfhle As you can check in this CodeSandBox, even when I call the state updater with the same value as the current state, it still re-renders the component.

Hi Alan, you’re right, it’s not completely true. From the documentation: > If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.) > Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go ‘deeper’ into the tree.

So it doesn’t always skip the rendering. I’ll update this part of the article. Thank you so much!

This is likely a very elementary, basic JS question, but I’m learning.

Why did you pass the anonymous function that returns the result of expensiveComputation into useState… instead of just passing the result of expensiveComputation itself?

In this line: const messageState = useState( () => expensiveComputation() );

Thank you. Once again I know this isn’t a react question but a JS question. Thank you for the clarification. My newbie skills will thank you!

the argument is evaluated every time the component is re-rendered. If you pass the result of expensiveComputation directly, it will be recalculated on every render, which can lead to performance issues.

I can see why a call to useState() shouldn’t be mixed into branching code (ifs, loops etc), because the identity of the state is dictated by the order of useState() calls within the stateless function call.

However, I can’t see why having calls to the setMessage function in branching code below would be a problem (as per your example code quoted below).

That’s because once the setMessage reference has been created, the association between the function and the specific state hook has been established, and any call to setMessage or setList will manipulate the correct value.

In fact I don’t think hooks could work at all if the order of state hook _setting_ calls had to be predictable, so I don’t think there’s anything wrong with the code example.

By contrast if the useState() call was conditionally called (e.g. based on props), then any state established by a later useState call would have an unpredictable identity on the second render.

const [message, setMessage] = useState( ” ); const [list, setList] = useState( [] ); if (condition) { setMessage( aMessage ); // Sometimes it will be executed, making the order change } setList( [1, 2, 3] );

Hi Cefn. Sorry for the late response, you are right, that was a bad example, I have updated the sample code to place the call to useState inside the if block. Thank you so much!

Hi SpidaFly, sorry for the late response, and no problem at all answering your question. If we have an expression like this: let result = expensiveComputation();

It will be evaluated immediately, blocking the execution of the code until the method returns.

On the other hand, something like this: let result = () => expensiveComputation();

Returns a function that is not executed when the line is evaluated, so the execution of the code is not blocked at that particular time. The function is executed only when you can it ( result() ), if ever. That’s the benefit of laziness ( https://en.wikipedia.org/wiki/Lazy_evaluation ).

Hope this answers your question!

Hi There is a typo in the name of useState function in the following line:

“This article is a guide to the useSate (state) hook, the equivalent of this.state/this.setSate for functional components.|

It seems that the initial statement made in the article is true in v16.8.0 and above. I changed the react version in your CodeSandBox and true enough, React doesn’t seem to trigger a re-render if the value is the same as the current state.

This article should be the offical documentation of the useState hook. Well done.

{ const val = e.target.value; setMessage(prev => prev + val) } } />

In this, I do not seem to understand how “prev” refers to the ACTUAL PREVIOUS value of input ??

Thanks for the great article! I have a question about the ‘here’s how you’d update the author field of the state object’ section. Should this not be setMessageObj((prevState) => ({ …prevState, // copy all other field/objects author: “Joe” // overwrite the value of the field to update }))

As far as I understant, if the message child object has not changed, we can use the spread operator to copy all values as-is, then we just overwrite the author field on the top level of the state object.

Very helpful article. thank you very much👍🏽

Thanks for the extremely helpful article! “If you use the previous value to update state, you must pass a function that receives the previous value and returns the new value” Not really, in the example given, setMessage(message + val) will work. But because message will only change after next rerender, if you call setMessage(message + val) multiple times, only one will work, and in that case you need the callback to do the trick

Leave a Reply Cancel reply

Using destructuring assignment in React

by Nathan Sebhastian

Posted on Nov 19, 2020

Reading time: 3 minutes

assignment to constant variable react

Destructuring assignment is a feature of JavaScript introduced by ES6 (or ES 2015) that’s available for both object and array data types. It allows you to assign the values of an array or the properties of an object without needing to reference the variable directly in the assignment.

Here’s the traditional way of assigning a value to a variable in JavaScript:

With destructuring assignment, your code will look like this:

You just turned two lines of assignment into one. Awesome, right? The same is also possible with an array, but instead of using curly brackets( {} ) you need to use square brackets ( [] ) on the assignment:

In fact, the useState hook from React returns an array with two values that we destructure immediately. Here’s an illustration of how it works:

The benefits of using destructuring assignment is especially visible when using React because you would deal with state and props frequently. For example, a functional component may receive a single prop object with many properties like this:

When you need to display the props in your interface, you’d probably pass the prop into the component and use the value with props. syntax:

Yikes! Look at how long the syntax just for displaying a name. When using destructuring assignment, you can reduce that long syntax and make it better. First, destructure the userData props before passing it to the component:

Then pass it into the component as two props:

Or you can also use spread operator so you don’t need to destructure it:

Then immediately destructure the props object when you define the parameters in the function, like this:

And now you can use the arguments inside your props with less repetition:

Want even less repetition? You can even destructure nested properties with JavaScript!

Here’s a Code Sandbox example that you can tweak with.

The syntax looks a bit complicated at first, so here’s how to make destructuring easy in two steps process:

First, you need to find the name of the properties you want to extract first. In the example, the goal is to extract loggedIn , firstName , lastName , and email properties:

First and Second-level properties in JS object

After that, you simply find the first-level properties that hold the second-level properties. Write the property name:

Then write the desired properties inside the curly brackets:

The same could also be applied in class-based components. You simply destructure the props in your render() function:

And that’s it. Destructuring assignment is a wonderful feature from ES6 that really helps you to avoid repetition and keep your code clean. You can extract nested properties of an object and simply use them inside your render function.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

Is your WordPress site slow? Get a free audit to uncover performance bottlenecks.

JavaScript Features You Need to Know to Master React

Understanding JavaScript and React

These days, React is one of the most popular JavaScript libraries . It can be used to create dynamic and responsive applications, allows for better performance, and can be easily extended. The underlying logic is based on components that can be reused in different contexts, reducing the need to write the same code several times. In short, with React you can create efficient and powerful applications .

So there has never been a better time to learn how to create React applications.

However, without a solid understanding of some key JavaScript features, building React applications might be difficult or even impossible.

For this reason, we have compiled a list of JavaScript features and concepts that you need to know before getting started with React. The better you understand these concepts, the easier it will be for you to build professional React applications.

JavaScript and ECMAScript

JavaScript is a popular scripting language used together with HTML and CSS to build dynamic web pages. While HTML is used to create the structure of a web page and CSS to create the style and layout of its elements, JavaScript is the language used to add behavior to the page, i.e. to create functionality and interactivity.

The language has since been adopted by the major browsers and a document was written to describe the way JavaScript was intended to work: the ECMAScript standard .

As of 2015, an update of the ECMAScript standard is released annually, and thus new features are added to JavaScript every year.

ECMAScript 2015 was the sixth release of the standard and is therefore also known as ES6 . Following versions are marked in progression, so we refer to ECMAScript 2016 as ES7, ECMAScript 2017 as ES8, and so on.

Due to the frequency with which new features are added to the standard, some may not be supported in all browsers. So how could you make sure that the latest JavaScript features you added to your JS app would work as expected across all web browsers?

You have three options:

  • Wait until all major browsers provide support for the new features. But if you absolutely need that amazing new JS feature for your app, this is not an option.
  • Use a Polyfill, which is “a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it” (see also mdn web docs ).
  • Use a JavaScript transpiler such as Babel or Traceur , that convert ECMAScript 2015+ code into a JavaScript version that is supported by all browsers.

Statements vs Expressions

Understanding the difference between statements and expressions is essential when building React applications. So, let us go back to the basic concepts of programming for a moment.

A computer program is a list of instructions to be executed by a computer. These instructions are called statements .

Unlike statements, expressions are fragments of code that produce a value. In a statement, an expression is a part that returns a value and we usually see it on the right side of an equal sign.

JavaScript statements can be blocks or lines of code that usually end with semicolons or are enclosed in curly brackets.

Here is a simple example of a statement in JavaScript:

The statement above writes "Hello World!" in a DOM element with id="hello" .

As we already mentioned, expessions produce a value or are themselves a value. Consider the following example:

document.getElementById("hello").value is en expression as it returns a value.

An additional example should help clarify the difference between expressions and statements:

In the example above,

  • the first line is a statement, where "Hello World!" is an expression,
  • the function declaration is a statement, where the parameter msg passed to the function is an expression,
  • the line that prints the message in the console is a statement, where again the parameter msg is an expression.

Why Expressions Are Important in React

When building a React application , you can inject JavaScript expressions into your JSX code . For example, you can pass a variable, write an event handler or a condition. To do this, you need to include your JS code in curly brackets.

For example, you can pass a variable:

In short, the curly brackets tell your transpiler to process the code wrapped in brackets as JS code. Everything that comes before the opening <p> tag and after the closing </p> tag is normal JavaScript code. Everything inside the opening <p> and closing </p> tags is processed as JSX code.

Here is another example:

You can also pass an object:

And below is a more comprehensive example:

Notice the double curly brackets in the style attributes in the elements img and div . We used double brackets to pass two objects containing card and image styles.

An example card built with React

You should have noticed that in all the examples above, we included JavaScript expressions in JSX .

Immutability in React

Mutability and Immutability are two key concepts in object-oriented and functional programming.

Immutability means that a value cannot be changed after it has been created. Mutability means, of course, the opposite.

In Javascript, primitive values are immutable , meaning that once a primitive value is created, it cannot be changed. Conversely, arrays and objects are mutable because their properties and elements can be changed without reassigning a new value.

There are several reasons for using immutable objects in JavaScript:

  • Improved performance
  • Reduced memory consumption
  • Thread-safety
  • Easier coding and debugging

Following the pattern of immutability, once a variable or object is assigned, it cannot be re-assigned or changed. When you need to modify data, you should create a copy of it and modify its content, leaving the original content unchanged.

Immutability is also a key concept in React.

The React documentation states:

The state of a class component is available as this.state . The state field must be an object. Do not mutate the state directly. If you wish to change the state, call setState with the new state.

Whenever the state of a component changes, React calculates whether to re-render the component and update the Virtual DOM. If React did not have track of the previous state, it could not determine whether to re-render the component or not. React documentation provides an excellent example of this .

What JavaScript features can we use to guarantee the immutability of the state object in React? Let’s find out!

Declaring Variables

You have three ways to declare a variable in JavaScript: var , let , and const .

The var statement exists since the beginning of JavaScript. It’s used to declare a function-scoped or globally-scoped variable, optionally initializing it to a value.

When you declare a variable using var , you can re-declare and update that variable both in the global and local scope. The following code is allowed:

var declarations are processed before any code is executed. As a result, declaring a variable anywhere in the code is equivalent to declaring it at the top. This behavior is called hoisting .

It is worth noting that only the variable declaration is hoisted, not the initialization, which only happens when the control flow reaches the assignment statement. Until that point, the variable is undefined :

The scope of a var declared in a JS function is the whole body of that function .

This means that the variable is not defined at block level, but at the level of the entire function. This leads to a number of problems that can make your JavaScript code buggy and difficult to maintain.

To fix these problems, ES6 introduced the let keyword .

The let declaration declares a block-scoped local variable, optionally initializing it to a value.

What are the advantages of let over var ? Here are some:

  • let declares a variable to the scope of a block statement , while var declares a variable globally or locally to an entire function regardless of block scope.
  • Global let variables are not properties of the window object . You cannot access them with window.variableName .
  • let can only be accessed after its declaration is reached . The variable is not initialized until the control flow reaches the line of code where it’s declared (let declarations are non-hoisted ).
  • Redeclaring a variable with let throws a SyntaxError .

Since variables declared using var cannot be block-scoped, if you define a variable using var in a loop or inside an if statement, it can be accessed from outside the block and this can lead to buggy code.

The code in the first example is executed without errors. Now replace var with let in the block of code seen above:

In the second example, using let instead of var produces an Uncaught ReferenceError :

Uncaught ReferenceError in Chrome

ES6 also introduces a third keyword: const .

const is pretty similar to let , but with a key difference:

Consider the following example:

The above code would generate the following TypeError :

Uncaught TypeError: Assignment to constant variable in Google Chrome

In addition:

Declaring a const without giving it a value would throw the following SyntaxError (see also ES6 In Depth: let and const ):

Uncaught SyntaxError: Missing initializer in const declaration in Chrome

But if a constant is an array or an object, you can edit properties or items within that array or object.

For example, you can change, add, and remove array items:

But you are not allowed to reassign the array:

The code above would result in a TypeError .

Uncaught TypeError: Assignment to constant variable.

You can add, reassign, and remove object properties and methods:

But you are not allowed to reassign the object itself. The following code would go through an Uncaught TypeError :

Object.freeze()

We now agree that using const does not always guarantee strong immutability (especially when working with objects and arrays). So, how can you implement the immutability pattern in your React applications?

First, when you want to prevent the elements of an array or properties of an object from being modified, you can use the static method Object.freeze() .

Freezing an object prevents extensions and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object’s prototype cannot be re-assigned. freeze() returns the same object that was passed in.

Any attempt to add, change or remove a property will fail, either silently or by throwing a TypeError , most commonly in strict mode .

You can use Object.freeze() this way:

If you now try to add a property, you will receive an Uncaught TypeError :

Uncaught TypeError: can't define property

When you try to reassign a property, you get another kind of TypeError :

Reassign a read-only property throws an Uncaught TypeError

You can also try to delete a property. The result will be another TypeError :

Uncaught TypeError: property

Template Literals

When you need to combine strings with the output of expressions in JavaScript, you usually use the addition operator + . However, you can also use a JavaScript feature that allows you to include expressions within strings without using the addition operator: Template Literals .

Template Literals are a special kind of strings delimited with backtick ( ` ) characters.

In Template Literals you can include placeholders, which are embedded expressions delimited by a dollar character and wrapped in curly brackets.

Here is an example:

The strings and placeholders get passed to a default function that performs string interpolation to substitute the placeholders and concatenate the parts into a single string. You can also replace the default function with a custom function.

You can use Template Literals for:

Multi-line strings : newline characters are part of the template literal.

String interpolation : Without Template Literals, you can only use the addition operator to combine the output of expressions with strings. See the following example:

It’s a bit confusing, isn’t it? But you can write that code in a more readable and maintainable way using Template Literals:

But keep in mind that there’s a difference between the two syntaxes :

Template Literals lend themselves to several uses. In the following example, we use a ternary operator to assign a value to a class attribute.

Below, we are performing a simple calculation:

It is also possible to nest Template Literals by including them inside an ${expression} placeholder (but use nested templates with caution because complex string structures may be hard to read and maintain).

Tagged templates : As we mentioned above, it is also possible to define a custom function to perform string concatenation. This kind of Template Literal is called Tagged Template .

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

Tags allow you to parse template literals with a custom function. The first argument of this function is an array of the strings included in the Template Literal, the other arguments are the expressions.

You can create a custom function to perform any sort of operation on the template arguments and return the manipulated string. Here is a very basic example of tagged template :

The code above prints the strings and tags array elements then capitalizes the string characters before printing the output in the browser console.

Arrow Functions

Arrow functions are an alternative to anonymous functions (functions without names) in JavaScript but with some differences and limitations.

The following declarations are all valid Arrow Functions examples:

You may omit the round brackets if you only pass one parameter to the function. If you pass two or more parameters, you must enclose them in brackets. Here is an example of this:

One-line Arrow Functions return a value by default. If you use the multiple-line syntax, you will have to manually return a value:

One key difference between normal functions and Arrow Functions to bear in mind is that Arrow functions don’t have their own bindings to the keyword this . If you try to use this in an Arrow Function, it will go outside the function scope.

For a more in-depth description of Arrow functions and examples of use, read also mdn web docs .

Classes in JavaScript are a special type of function for creating objects that use the prototypical inheritance mechanism.

According to mdn web docs ,

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.

As with functions, you have two ways of defining a class:

  • A class expression
  • A class declaration

You can use the class keyword to define a class inside an expression, as shown in the following example:

A class has a body, that is the code included in curly brakets. Here you’ll define constructor and methods, which are also called class members. The body of the class is executed in strict mode even without using the 'strict mode' directive.

The constructor method is used for creating and initializing an object created with a class and is automatically executed when the class is instantiated. If you don’t define a constructor method in your class, JavaScript will automatically use a default constructor.

A class can be extended using the extends keyword.

A constructor can use the super keyword to call the parent constructor. If you pass an argument to the super() method, this argument will also be available in the parent constructor class.

For a deeper dive into JavaScript classes and several examples of usage, see also the mdn web docs .

Classes are often used to create React components. Usually, you’ll not create your own classes but rather extend built-in React classes.

All classes in React have a render() method that returns a React element:

In the example above, Animal is a class component. Bear in mind that

  • The name of the component must begin with a capital letter
  • The component must include the expression extends React.Component . This gives access to the methods of the React.Component .
  • The render() method returns the HTML and is required.

Once you have created your class component, you can render the HTML on the page:

The image below shows the result on the page (You can see it in action on CodePen ).

A simple React class component

Note, however, that using class components in React is not recommended and it’s preferable defining components as functions .

The Keyword ‘this’

In JavaScript, the this keyword is a generic placeholder usually used inside objects, classes, and functions, and it refers to different elements depending on the context or scope.

this can be used in the global scope. If you digit this in your browser’s console, you get:

You can access any of the methods and properties of the Window object. So, if you run this.location in your browser’s console, you get the following output:

When you use this in an object, it refers to the object itself. In this way, you can refer to the values of an object in the methods of the object itself:

Now let’s try to use this in a function:

If you are not in strict mode, you’ll get:

But if you invoke strict mode , you get a different result:

In this case, the function returns undefined . That’s because this in a function refers to its explicit value.

So how to explicitly set this in a function?

First, you can manually assign properties and methods to the function:

But you can also use call , apply , and bind methods, as well as arrow functions.

The call() method can be used on any function and does exactly what it says: it calls the function.

Furthermore, call() accepts any other parameter defined in the function:

An alternative to the options discussed above is using arrow functions .

Arrow function expressions should only be used for non-method functions because they do not have their own this .

This makes arrow functions particularly useful with event handlers.

That’s because “when the code is called from an inline event handler attribute, its this is set to the DOM element on which the listener is placed” (see mdn web docs ).

But things change with arrow functions because…

… arrow functions establish this based on the scope the arrow function is defined within, and the this value does not change based on how the function is invoked.

Binding ‘this’ to Event Handlers in React

When it comes to React, you have a few ways to make sure that the event handler does not lose its context:

1. Using bind() inside the render method:

2. Binding the context to the event handler in the constructor:

3. Define the event handler using arrow functions:

4. Using arrow functions in the render method:

Whichever method you choose, when you click the button, the browser console shows the following output:

Ternary Operator

The conditional operator (or ternary operator) allows you to write simple conditional expressions in JavaScript. It takes three operands:

  • a condition followed by a question mark ( ? ),
  • an expression to execute if the condition is truthy followed by a colon ( : ),
  • a second expression to execute if the condition is falsy .

It is also possible to chain multiple expressions:

Be careful, though, because chaining multiple expressions can lead to messy code that is difficult to maintain.

The ternary operator is particularly useful in React, especially in your JSX code, which only accepts expressions in curly brackets.

For example, you can use the ternary operator to set the value of an attribute based on a specific condition:

In the code above, we check the condition person.theme === 'dark' to set the value of the style attribute of the container div .

Short Circuit Evaluation

The logical AND ( && ) operator evaluates operands from left to right and returns true if and only if all operands are true .

The logical AND is a short-circuit operator . Each operand is converted to a boolean and, if the result of the conversion is false , the AND operator stops and returns the original value of the falsy operand. If all values are true , it returns the original value of the last operand.

Short circuit evaluation is a JavaScript feature commonly used in React as it allows you to output blocks of code based on specific conditions. Here is an example:

In the code above, if displayExcerpt AND post.excerpt.rendered evaluate to true , React returns the final block of JSX.

To recap , “if the condition is true , the element right after && will appear in the output. If it is false , React will ignore and skip it”.

Spread Syntax

In JavaScript, spread syntax allows you to expand an iterable element, such as an array or object, into function arguments, array literals, or object literals.

In the following example, we are unpacking an array in a function call:

You can use the spread syntax to duplicate an array (even multidimensional arrays) or to concatenate arrays. In the following examples, we concatenate two arrays in two different ways:

Alternatively:

You can also use the spread syntax to clone or merge two objects:

Destructuring Assignment

Another syntactic structure you will often find used in React is the destructuring assignment syntax.

In the following example, we unpack values from an array:

And here is a simple example of destructuring assignment with an object:

But we can do even more. In the following example, we unpack some properties of an object and assign the remaining properties to another object using the spread syntax:

You can also assign values to an array:

Note that the parentheses around the assignment statement are required when using object literal destructuring assignment without a declaration.

For a more in-depth analysis of destructuring assignment, with several examples of use, please refer to the mdn web docs .

filter(), map(), and reduce()

JavaScript provides several useful methods you’ll find often used in React.

In the following example, we apply the filter to the numbers array to get an array whose elements are numbers greater than 5:

In the following example, we get an array of posts with the word ‘JavaScript’ included in the title:

An array of posts where the title includes 'JavaScript'

In a React component, you’ll often find the map() method used to build lists. In the following example, we’re mapping the WordPress posts object to build a list of posts :

reduce() accepts two parameters:

  • A callback function to execute for each element in the array. It returns a value that becomes the value of the accumulator parameter on the next call. On the last call, the function returns the value that will be the return value of reduce() .
  • An initial value that is the first value of the accumulator passed to the callback function.

The callback function takes a few parameters:

  • An accumulator : The value returned from the previous call to the callback function. On the first call, it’s set to an initial value if specified. Otherwise, it takes the value of the first item of the array.
  • The value of the current element : The value is set to the first element of the array ( array[0] ) if an initial value has been set, otherwise it takes the value of the second element ( array[1] ).
  • The current index is the index position of the current element.

An example will make everything clearer.

Let’s find out in detail what happens at each iteration. Go back to the previous example and change the initialValue :

The following image shows the output in the browser console:

using reduce() with initial value set to 5

Now let us find out what happens without the initialValue parameter:

Using reduce() without initial value

More examples and use cases are discussed on the mdn web docs website.

Exports and Imports

As of ECMAScript 2015 (ES6), it is possible to export values from a JavaScript module and import them into another script. You’ll be using imports and exports extensively in your React applications and therefore it is important to have a good understanding of how they work.

The following code creates a functional component. The first line imports the React library:

We used the import keyword followed by the name we want to assign to what we are importing, followed by the name of the package we want to install as it is referred to in the package.json file.

Note that in the MyComponent() function above, we used some of the JavaScript features discussed in the previous sections. We included property values in curly brackets and assigned the value of the style property using the conditional operator syntax.

The script ends with the export of our custom component.

Now that we know a bit more about imports and exports, let’s take a closer look at how they work.

Every React module can have two different types of export : named export and default export .

For example, you can export several features at once with a single export statement:

You can also export individual features ( function , class , const , let ):

But you can only have a single default export:

You can also use default export for individual features:

Once the component has been exported, it can be imported into another file, e.g. an index.js file, along with other modules:

In the code above, we used the import declaration in several ways.

In the first two lines, we assigned a name to the imported resources, in the third line we did not assign a name but simply imported the ./index.css file. The last import statement imports the ./MyComponent file and assigns a name.

Let’s find out the differences between those imports.

In total, there are four types of imports:

Named import

Default import

Namespace import

Side effect import

Once you have added a few styles in your index.css , your card should look like in the image below, where you can also see the corresponding HTML code:

A simple React component

Note that import declarations can only be used in modules at the top level (not inside functions, classes, etc.).

For a more comprehensive overview of import and export statements, you may also want to check the following resources:

  • export (mdn web docs)
  • import (mdn web docs)
  • Importing and Exporting Components (React dev)
  • When should I use curly braces for ES6 import? (Stack Overflow)

React is one of the most popular JavaScript libraries today and is one of the most requested skills in the world of web development .

With React, it is possible to create dynamic web applications and advanced interfaces. Creating large, dynamic, and interactive applications can be easy thanks to its reusable components.

But React is a JavaScript library, and a good understanding of the main features of JavaScript is essential to start your journey with React. That’s why we’ve collected in one place some of the JavaScript features you’ll find most often used in React. Mastering those features will give you a leg up on your React learning journey .

And when it comes to web development , making the move from JS/React to WordPress takes very little effort.

Now it’s your turn, what JavaScript features do you think are most useful in React development? Have we missed anything important that you would have liked to see on our list? Share your thoughts with us in the comments below.

assignment to constant variable react

Carlo is a passionate lover of webdesign and front-end development. He has been playing with WordPress for more than 20 years, also in collaboration with Italian and European universities and educational institutions. He has written hundreds of articles and guides about WordPress, published both on Italian and international websites, as well as on printed magazines. You can find him on LinkedIn .

Related Articles and Topics

assignment to constant variable react

Powerful Managed WordPress Hosting

assignment to constant variable react

62 Awesome Web Development Tools to Use

  • Local Development
  • Application 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.

TypeError: Assignment to constant variable when using React useState hook

Abstract: Learn about the common error 'TypeError: Assignment to constant variable' that occurs when using the React useState hook in JavaScript. Understand the cause of the error and how to resolve it effectively.

If you are a React developer, you have probably come across the useState hook, which is a powerful feature that allows you to manage state in functional components. However, there may be times when you encounter a TypeError: Assignment to constant variable error while using the useState hook. In this article, we will explore the possible causes of this error and how to resolve it.

Understanding the Error

The TypeError: Assignment to constant variable error occurs when you attempt to update the value of a constant variable that is declared using the const keyword. In React, when you use the useState hook, it returns an array with two elements: the current state value and a function to update the state value. If you mistakenly try to assign a new value to the state variable directly, you will encounter this error.

Common Causes

There are a few common causes for this error:

  • Forgetting to invoke the state update function: When using the useState hook, you need to call the state update function to update the state value. For example, instead of stateVariable = newValue , you should use setStateVariable(newValue) . Forgetting to invoke the function will result in the TypeError: Assignment to constant variable error.
  • Using the wrong state update function: If you have multiple state variables in your component, make sure you are using the correct state update function for each variable. Mixing up the state update functions can lead to this error.
  • Declaring the state variable inside a loop or conditional statement: If you declare the state variable inside a loop or conditional statement, it will be re-initialized on each iteration or when the condition changes. This can cause the TypeError: Assignment to constant variable error if you try to update the state value.

Resolving the Error

To resolve the TypeError: Assignment to constant variable error, you need to ensure that you are using the state update function correctly and that you are not re-declaring the state variable inside a loop or conditional statement.

If you are forgetting to invoke the state update function, make sure to add parentheses after the function name when updating the state value. For example, change stateVariable = newValue to setStateVariable(newValue) .

If you have multiple state variables, double-check that you are using the correct state update function for each variable. Using the wrong function can result in the error. Make sure to match the state variable name with the corresponding update function.

Lastly, if you have declared the state variable inside a loop or conditional statement, consider moving the declaration outside of the loop or conditional statement. This ensures that the state variable is not re-initialized on each iteration or when the condition changes.

The TypeError: Assignment to constant variable error is a common mistake when using the useState hook in React. By understanding the causes of this error and following the suggested resolutions, you can overcome this issue and effectively manage state in your React applications.

Tags: :  javascript reactjs react-state

Latest news

  • Compile-Time Validation of Strings: Making It Work with C++
  • Reloading and Redrawing WaveSurferJS: Applying Changes
  • VS Professional: Handling Multiple Subfolders in a CMake Project
  • Can't Send Key Twitter XPath: Get Error with Twitter Updated Today?
  • Error in Scholarship Request Class for Middleware User Registration
  • Unable to Run Program using GoCV: Opencv Module Missing
  • Git Submodule Update: Specifying a Branch
  • Running an Android Studio Project on Multiple Devices: A Step-by-Step Guide
  • Fix: Objects not valid as React child (found: object keys {}). React for Private Pages
  • Inferring DataFrame Schema with R: A Practical Example
  • Clonezilla: Creating a System Image without Installing New Programs
  • Resolving Pip Install Failure for pandas on Windows
  • Creating Python Bindings for a Base Class with __repr__ in C++ using pybind11
  • Resolving Core Issues: Sending Firebase Notifications in a Flutter Web Release App
  • Understanding the Difference: Using `useEffect` with an Empty Dependency Array in a Conditional
  • Restricting Access to PHPMyAdmin on Apache Servers with Specific IP Addresses
  • Obtaining UUID Number in Flutter Raspberry Pi Application: Solving Linux Permission Errors
  • Azure WebApp Error: 'URL results' resource looking removed or name changed in ASP.Net 8.0 WebAPI application
  • Setting Global No-Index for Multiple Domains on Dokku Server
  • App Doesn't Rotate on ConfigurationChanged not Called (API 30)
  • Understanding Lifetime Callbacks with JSInterop in C# WASM
  • Creating a Dashboard View for Test Execution Progress: A Performance Tester's Perspective (KIWI)
  • Find Difference: Today Event Date vs. 10 Days Ago in Excel
  • Calculating Number of Farms Needed for Chicken Housing: Rotational Barn Usage in TypeScript
  • Using Tailwind CSS for Grid-Based Layouts: row-start and row-end behaviors
  • Copying Files in Azure Function App: A Workaround
  • Enforcing Functions to Take a Props Object with ESLint: rule 'function-args-type'
  • Using Webflow CMS Components Together: Unexpected Issues Encountered
  • Persistent Connection Issue with Dockerized Go Application using Go-Liftbridge Client and Liftbridge Service
  • Handling Uncaught Exceptions in Node.js: Error: No responder returned route handler
  • Loading Large Data Set: UI Server Response Object
  • Setting up Automation Testing with Selenium 4.20.0 and Chrome 124
  • Cookie Consent: Product Lists Stop Loading After User Declines Cookies
  • Compiling Qt <QDateTime> File using C++: A Content Class Example
  • Draggable Bottom Sheet: TabView Rendering Issues

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.

assignment to constant variable react

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

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

error Assignment to constant variable. #2350

@rajak9930

rajak9930 commented Feb 19, 2024 • edited

@rajak9930

akiran commented Feb 19, 2024 • edited

Sorry, something went wrong.

@akiran

No branches or pull requests

@akiran

  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • Web Technology

How to declare constant in react class ?

  • How to create Class Component in React?
  • How to Declare a Constant Variable in JavaScript ?
  • How to declare a Constant Variable in PHP?
  • How to Define Constants in C++?
  • How to create a form in React?
  • How to create components in ReactJS ?
  • How to create a rating component in ReactJS ?
  • How to create a Functional Component in React?
  • How to determine the size of a component in ReactJS ?
  • How to convert functional component to class component in ReactJS ?
  • How are React Hooks different from class components in ReactJS?
  • How to use Badge Component in ReactJS?
  • How to create sticky footer in ReactJS ?
  • How to implement class constants in TypeScript ?
  • How do you initialize state in a class component?
  • How to Declare a Variable in JavaScript ?
  • How to get single cache data in ReactJS ?
  • How to add Stateful component without constructor class in React?
  • Different ways to declare variable as constant in C

To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that constant is accessible class-wide. Constants can be declared in the following two ways:

  • Create a getter method in the class for getting the constant when required.
  • Assign the class constant after the declaration of the class. 

Create a sample project with the following command:

Now move to the constantDemo folder using the following command:

The Project Structure will look like the following:

assignment to constant variable react

Filename: App.js Now open the App.js file and paste the following code in it:

Now run the project using the following command:

Output : 

assignment to constant variable react

Another way of declaring the constants is shown below. Paste down the following code in the App.js file.

Filename: App.js

assignment to constant variable react

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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?

assignment to constant variable react

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…

assignment to constant variable react

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.

assignment to constant variable react

More than 1 year has passed since last update.

assignment to constant variable react

【React】TypeError: Assignment to constant variableの対処法

下記ソースを実行したときに、TypeError: Assignment to constant variableが発生してしまいました。 翻訳すると、「TypeError: 定数変数への代入」という内容でした。

定数に対して再度値を代入しようとしていたため、起きていたようです。 useEffect内で代入せず、useStateやuseReduverで値を管理するとよさそうです。

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme

COMMENTS

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

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

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

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

  4. 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: js.

  5. React ES6 Variables

    React ES6 Variables ... If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block. var has a function scope, not a block scope. ... It does not define a constant value. It defines a constant reference to a value. Because of this you can NOT:

  6. useState in React: A complete guide

    Implementing an object as a state variable with useState Hook. There are two things you need to keep in mind about updates when using objects: The importance of immutability; And the fact that the setter returned by useState doesn't merge objects like setState() does in class components; About the first point, if you use the same value as the current state to update the state (React uses ...

  7. Using destructuring assignment in React

    Destructuring assignment is a feature of JavaScript introduced by ES6 (or ES 2015) that's available for both object and array data types. It allows you to assign the values of an array or the properties of an object without needing to reference the variable directly in the assignment. Here's the traditional way of assigning a value to a ...

  8. ES6 Variables in React.js

    ES6 introduced let and const to solve these issues: let is like var, but it limits the variable's scope to the block in which it is declared. const is similar to let, but it prevents reassigning ...

  9. JavaScript Features You Need to Know to Master React

    Uncaught TypeError: Assignment to constant variable in Google Chrome. In addition: ️ You can't declare a const without giving it a value. ... ️ In React, declaring variables with const is the default. let should be used when const is not appropriate. Using var is highly discouraged.

  10. TypeError: Assignment to constant variable. #16211

    Do you want to request a feature or report a bug? bug What is the current behavior? TypeError: Assignment to constant variable. System: OSX npm: 6.10.2 node: v10.13. react: 16.8.6

  11. TypeError: Assignment to constant variable when using React useState hook

    TypeError: Assignment to constant variable when using React useState hook. If you are a React developer, you have probably come across the useState hook, which is a powerful feature that allows you to manage state in functional components.

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

  13. error Assignment to constant variable. · Issue #2350 · akiran/react

    import { Link } from "react-router-dom"; import Slider from "react-slick"; const CustomersAry = [ { id: "01", title: ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quis ipsum suspendisse ultrices gravida.

  14. How to declare constant in react class

    Constants can be declared in the following two ways: Create a getter method in the class for getting the constant when required. Assign the class constant after the declaration of the class. Create a sample project with the following command: // constantDemo is the name of our folder. npx create-react-app constantDemo.

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

  16. How to Fix Assignment to Constant Variable

    Solution 2: Choose a New Variable Name. Another solution is to select a different variable name and declare it as a constant. This is useful when you need to update the value of a variable but want to adhere to the principle of immutability.

  17. How come, we can modify the const variable in react but not in ...

    The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). useState doesn't reassign anything. It just updates the value that goes to the state variable upon execution of the component function (a rerender).

  18. 【React】TypeError: Assignment to constant variableの対処法

    症状. 下記ソースを実行したときに、TypeError: Assignment to constant variableが発生してしまいました。 翻訳すると、「TypeError: 定数変数への代入」という内容でした。

  19. node.js

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