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

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript const.

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Must be Assigned

JavaScript const variables must be assigned a value when they are declared:

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Constant Objects and Arrays

The keyword const is a little 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

Constant Arrays

You can change the elements of a constant array:

But you can NOT reassign the array:

Constant Objects

You can change the properties of a constant object:

But you can NOT reassign the object:

Difference Between var, let and const

ScopeRedeclareReassignHoistedBinds this
varNoYesYesYesYes
letYesNoYesNoNo
constYesNoNoNoNo

What is Good?

let and const have block scope .

let and const can not be redeclared .

let and const must be declared before use.

let and const does not bind to this .

let and const are not hoisted .

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.

Browser Support

The let and const keywords are not supported in Internet Explorer 11 or earlier.

The following table defines the first browser versions with full support:

Chrome 49 Edge 12 Firefox 36 Safari 11 Opera 36
Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017 Mar, 2016

Advertisement

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope .

The x declared in the block, in this example, is not the same as the x declared outside the block:

You can learn more about block scope in the chapter JavaScript Scope .

Redeclaring

Redeclaring a JavaScript var variable is allowed anywhere in a program:

Redeclaring an existing var or let variable to const , in the same scope, is not allowed:

Reassigning an existing const variable, in the same scope, is not allowed:

Redeclaring a variable with const , in another scope, or in another block, is allowed:

Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

This is OK:

Variables defined with const are also hoisted to the top, but not initialized.

Meaning: Using a const variable before it is declared will result in a ReferenceError :

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.

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

TypeError: invalid assignment to const "x"

Const and immutability, what went wrong.

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

Invalid redeclaration

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

Fixing the error

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

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

const , let or var ?

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

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

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

But you can mutate the properties in a variable:

Document Tags and Contributors

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

This web page has moved

  • “JavaScript for impatient programmers” is now “Exploring JavaScript”.
  • You’ll be transported to the new website .

JavaScript const

Are you ready to learn about the powerful JavaScript const keyword? Const is a way of declaring a variable that cannot be reassigned. It is a great way to ensure that your code is clean and maintainable by making sure that your variables are not changed accidentally. This tutorial will teach you all about the const keyword and how to use it in your JavaScript code.

Why should you use it?

  • It helps ensure that your variables are not changed accidentally.
  • It makes your code more maintainable and easier to debug.
  • It makes your code more secure by preventing malicious code from changing your variables.

Home » JavaScript Tutorial » JavaScript const: Declaring Constants in ES6

JavaScript const: Declaring Constants in ES6

Summary : in this tutorial, you’ll learn how to define constants by using the JavaScript const keyword.

Introduction to the JavaScript const keyword

ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value.

By convention, the constant identifiers are in uppercase.

Like the let keyword, the const keyword declares blocked-scope variables. However, the block-scoped variables declared by the const keyword can’t be reassigned .

The variables declared by the let keyword are mutable. It means that you can change their values anytime you want as shown in the following example:

However, variables created by the const keyword are “immutable”. In other words, you can’t reassign them to different values.

If you attempt to reassign a variable declared by the const keyword, you’ll get a TypeError like this:

Unlike the let keyword, you need to initialize the value to the variable declared by the const keyword.

The following example causes a SyntaxError due to missing the initializer in the const variable declaration:

JavaScript const and Objects

The const keyword ensures that the variable it creates is read-only. However, it doesn’t mean that the actual value to which the const variable reference is immutable. For example:

Even though the person variable is a constant, you can change the value of its property.

However, you cannot reassign a different value to the person constant like this:

If you want the value of the  person object to be immutable, you have to freeze it by using the Object.freeze() method:

Note that Object.freeze() is shallow, meaning that it can freeze the properties of the object, not the objects referenced by the properties.

For example, the company  object is constant and frozen.

But the company.address object is not immutable, you can add a new property to the company.address object as follows:

JavaScript const and Arrays

Consider the following example:

In this example, we declare an array colors that has one element using the const keyword. Then, we can change the array’s elements by adding the green color. However, we cannot reassign the array colors to another array.

JavaScript const in a for loop

ES6 provides a new construct called for...of that allows you to create a loop iterating over iterable objects such as arrays , maps , and sets .

If you don’t intend to modify the score variable inside the loop, you can use the const keyword instead:

In this example, the for...of    creates a new binding for the const keyword in each loop iteration. In other words, a new score constant is created in each iteration.

Notice that the const will not work in an imperative for loop. Trying to use the const keyword to declare a variable in the imperative for loop will result in a TypeError :

The reason is that the declaration is only evaluated once before the loop body starts.

  • The const keyword creates a read-only reference to a value. The readonly reference cannot be reassigned but the value can be changed.
  • The variables declared by the const keyword are blocked-scope and cannot be redeclared.

Declaring a Variable with const in JavaScript

Emmet Avatar

This tutorial will show you how to use the const keyword to declare a variable in JavaScript.

JavaScript const variable keyword

The const keyword is one of the three ways you can declare a variable in the JavaScript language.

What differentiates JavaScript’s const keyword from the others is that once a variable is declared, it cannot be assigned a new value.

This is incredibly useful when you need to declare a value that should never be changed during runtime. In fact, as a general rule, you should declare a variable using “ const ” unless you expect the value to be changed.

By the end of this guide, you should have a good understanding of how to declare a variable in JavaScript using const.

Syntax of the const Keyword in JavaScript

Let us start this section by showing you the syntax for JavaScript’s const keyword. You use this keyword just like any other way you would declare a variable.

You cannot declare a variable with const without assigning it a value. An empty constant is useless as it can never be assigned a value.

To declare a constant variable with the const keyword, you only need to use “ const ” followed by a variable name and then the value you want to be assigned to it.

For example, if we wanted to declare a variable called “ pimylifeup ” as a const while also assigning it the value “ pimylifeup.com “, you would use the following code.

A Const Variable cannot be Reassigned in JavaScript

One of the key points of using the const keyword to declare a variable in JavaScript is that you can never change its value.

The value you assign during declaration cannot be changed in almost all cases. However, there is a slight edge case that we will cover later on in this guide.

To showcase this, let us write a short JavaScript example where we declare a variable and then attempt to reassign its value.

Here we start by using the const keyword to declare our variable called “ website “. During the declaration we will assign our new variable the string "pimylifeup.com" .

After declaring the variable, we attempt to assign it a new value.This new value is "google.com" . Here is where an error would occur.

If you tried to run this example, you would recieve the following error message.

A Const Variable Must be Assigned a Value During Declaration

Another important thing to note about declaring a variable using JavaScript’s const keyword is that it must be declared with a value.

JavaScript will throw an error if you attempt to declare a const variable without setting a value.

The following is the correct way to declare a const variable in JavaScript

However, if you attempt to declare the variable using const without a value like shown below, you will run into an error.

Below is an example of the error message that JavaScript throws.

Object using JavaScript’s const Keyword

When you declare an object using JavaScript’s const keyword, you will find that you can still change the object’s properties.

This is because JavaScript declares a constant reference to the value. So while you can’t reassign the referenced value, you can adjust the properties of that referenced value.

Let us show this by writing a short example. With this example, we will declare a new object called “ website_post ” and give it two properties.

We then adjust two of the object’s properties and log the result. With this example, we aim to show you how the properties of an object can be changed even if it has been declared using the const keyword.

After running the above example, you should end up with the following within the terminal. Here you can see that even though the object was defined using “ const “, we could adjust the properties.

However, if you were to attempt to re-assign the value as we have shown below, you will run into an error.

If you use the example above, you will see the following error thrown by JavaScript.

Declaring an Array using JavaScript’s const Keyword

When you declare an array with the const keyword in JavaScript, you can still add, remove and change elements within the array.

While you can change elements of an array, it is crucial to note that you still can’t re-assign the variable. This is because when we change an element, we modify the referenced array, not the reference itself.

To showcase this, we will use JavaScript’s const keyword to declare an array called “ ages “. Within this array we will add a few random elements.

We then proceed to show you how you can adjust the elements within an array, by using the “ .pop() ” and “ .push() ” functions of the array.

After running the code, you should end up with the following result within the terminal. With this, you can see how we could re-adjust the elements within the array.

However, if you try re-assigning the array with a new value, you will run into an error. You can only adjust elements of the array.

Below is the sort of error you will see after trying to re-assign a variable after declaring it with the const keyword in JavaScript.

A const Variable has Block Scope

Like the let keyword, when you use const to declare a variable in JavaScript, it will have block scope.

Block scope is when JavaScript can’t access that variable when declared within a separate code block ( { } ). However, if declared in a parent code block, you can still access a const variable.

To showcase this behavior, we will write a short JavaScript example where we declare a const variable within a code block.

We will then use the “ console.log() ” function to try and output the value of this variable. This function call is what will show us how we can’t access the variable.

After running the above JavaScript, you will see the following error message.

One important thing to note about block scope is that you can declare a variable twice if they are within block different scopes.

While these variables can have the same name, they are considered entirely separate when defined in different blocks. Therefore, you will lose access to any variable using the same name declared in the parent block.

The example below showcases this behavior. You won’t run into a redeclaration error despite using the same variable name.

You will get two distinct values logged to the console if you run the above JavaScript.

This tutorial showed you how to use the const keyword to declare a variable.

A variable declared with const in JavaScript cannot have its value changed after assignment. However, you can still change the properties of objects.

Please comment below if you have any questions about using const in JavaScript.

To learn more, be sure to check out our other JavaScript tutorials . We also have other guides if you want to learn a new programming language .

Receive our Raspberry Pi projects, coding tutorials, Linux guides and more!

Thank you for subscribing

Recommended

Raspberry Pi TOR Access Point

Leave a Reply Cancel reply

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

  • JS if, else, & else if
  • JS Arithmetic
  • JS Assignment
  • JS Comparison
  • JS while Loop
  • JS do...while Loop
  • JS for Loop
  • JS for...in Loop
  • JS for...of Loop
  • JS continue
  • JS console.log()
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Output
  • JavaScript Comments

JS Variables & Datatypes

  • Variables and Datatypes in JavaScript
  • Global and Local variables in JavaScript
  • JavaScript Let

JavaScript Const

  • JavaScript var

JS Operators

  • JavaScript Operators
  • Operator precedence in JavaScript
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript Bitwise Operators
  • JavaScript Ternary Operator
  • JavaScript Comma Operator
  • JavaScript Unary Operators
  • JavaScript Relational operators
  • JavaScript String Operators
  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions

The const keyword in JavaScript is used to define variables that cannot be changed once they’re assigned a value. This prevents any modifications to the variable’s value.

Additionally, const doesn’t allow redeclaration of the same variable within the same block, and it provides block scope. It was introduced in ES2015 (ES6) for creating immutable variables.

Properties:

  • Cannot be reassigned.
  • It has Block Scope
  • It can be assigned to the variable on the declaration line.
  • It’s a Primitive value.
  • The property of a const object can be changed but it cannot be changed to a reference to the new object
  • The values inside the const array can be changed, it can add new items to const arrays but it cannot reference a new array.
  • Re-declaring of a const variable inside different block scopes is allowed.
  • Cannot be Hoisted.
  • Creates only read-only references to value.

Examples of JavaScript Const

Cannot be reassigned.

Example 1: It describes that the const variable cannot be reassigned. 

Example 2: It describes the const variable which contains the Block Scope. 

Variables must be Assigned

Example: It describes the const variable and assigned it after declaration. 

Output: 

Cannot be Hoisted

Example: It describes the const variable cannot be Hoisted. 

Const in Arrays

Example: It describes that the array values can be modified only reference to the array cannot be changed. 

Const in Objects

Example: It describes that the object properties can be modified only reference to the object cannot be changed. 

  Supported Browsers:

  • Google Chrome
  • Edge  

P.S: To clear your concept of var, const, and let please go through How to declare variables in different ways in JavaScript?

Please Login to comment...

Similar reads.

  • javascript-basics
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope

JavaScript Hoisting

  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Variable Scope

JavaScript let Vs var

JavaScript Destructuring Assignment

  • JavaScript Keywords and Identifiers
  • JavaScript null and undefined

JavaScript Variables and Constants

  • JavaScript Variables

A JavaScript variable is a container for storing data. For example,

Here, num is a variable that stores the number 5 .

  • Declare Variables in JavaScript

In JavaScript, we use the var or let keywords to declare variables. For example,

Here, age and name are variables.

Both var and let are used to declare variables. However, there are some differences between them.

var let
is used in older versions of JavaScript. is the new way of declaring variables, starting with .
Variables created with are , meaning they can be accessed anywhere within the function they were defined in. Variables declared with are block-scoped, meaning they can only be accessed within the block where they were declared.
For example, For example,

To learn more, visit JavaScript let Vs var .

Note: It is recommended we use let instead of var . However, there are a few browsers that do not support let . To learn more, visit JavaScript let browser support .

  • Initialize Variables in JavaScript

We use the assignment operator = to assign a value to a variable.

Here, 5 is assigned to the variable num .

You can also initialize variables during its declaration.

In JavaScript, it's possible to declare multiple variables in a single statement.

Here, we have declared and assigned values to three variables in a single line:

  • The value assigned to num1 is 5 .
  • The value assigned to num2 is 6 .
  • The value assigned to num3 is 7 .

If you use a variable without initializing it, it will have an undefined value.

Here, we have declared a variable named num . However, since it does not contain any value, its value is undefined .

To learn more about undefined , visit JavaScript null and undefined .

  • Change the Value of Variables

The value of a variable may vary . Hence, the name variable .

Let's look at the example below to learn how to change the value of a variable:

Here, the value of the score variable is changed from 5 to 3 when we assign a new value to it.

  • Rules for Naming JavaScript Variables
  • Variable names must start with a letter, an underscore _ , or the dollar sign $ . For example,
  • Variables cannot start with numbers. For example,
  • Variable names are case-sensitive. So age and Age are different variables. For example,
  • Variable names cannot be keywords (special words reserved for specific purposes in JavaScript such as if , else , let , var , etc.). For example,

You can name the variables any way you want. However, we recommend you use the following naming conventions:

  • In JavaScript, variables are generally named in camelCase format if they have multiple words. For example, firstName , annualSalary , numberOfBooks , etc.
  • It's a good practice to give a descriptive name to a variable. For example, if you are using a variable to store the number of apples, it is better to name that variable apples or numberOfApples rather than x or n .
  • JavaScript Constants

A constant is a type of variable whose value cannot be changed.

In JavaScript, we use the const keyword to create constants. For example,

Once a constant is initialized, we cannot change its value.

Always Initialize a Constant During Declaration

If you do not initialize a constant at the time of declaration, it throws an error. For example,

Note: If you are sure that the value of a variable won't change throughout the program, we recommend you use const .

However, there are a few browsers that do not support const . Visit JavaScript const browser support to learn more.

  • JavaScript Data Types

Table of Contents

Video: javascript variables.

Sorry about that.

Related Tutorials

JavaScript Tutorial

Marius Schulz

Constant Variables in JavaScript, or: When "const" Isn't Constant

ECMAScript 2015 introduced the let and const keywords as alternatives to var , which JavaScript has always had. Both let and const declare local variables with block scope rather than function scope . In addition, const provides some notion of constancy, which let doesn't.

Unfortunately, the name of the const keyword might be misleading. In JavaScript, const does not mean constant , but one-time assignment . It's a subtle yet important distinction. Let's see what one-time assignment means:

However, variables declared using the const keyword do not generally have a truly immutable value. Remember, const does not mean "constant", it means one-time assignment . The part that's constant is the reference to an object stored within the constant variable, not the object itself. The following example illustrates the difference:

Declaring a variable to be constant doesn't make the objects it references immutable, as the above example shows. Object properties can change or be deleted altogether. The same goes for arrays assigned to a constant variable; Elements can be added, removed, reordered, or modified:

For the sake of completeness, it is possible to create true constants in some cases. If a primitive value (such as a string, number, or boolean value) is assigned to a constant variable, that variable will be a true constant. Our PI constant is an example for this. There's no way to modify the value of the numeric literal 3.141592653589793 after it has been assigned.

To make an object truly immutable, you can pass it to the Object.freeze function to prevent any changes to its properties. Be aware that freeze is shallow, so you'll have to recursively call it for nested objects if you want the entire object tree to be frozen. If you need immutable data structures, it might be safer and more convenient to use a library such as Facebook's Immutable.js which is specifically made for this purpose.

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

Web Development

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

Published By: Divya Mahi

Published On: November 17, 2023

Published In: Development

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

Introduction.

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

Understanding the Error

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

Diving Deeper

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

Common Scenarios and Fixes

Example 1: reassigning a constant variable.

Javascript:

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

Example 2: Modifying an Object's Properties

Fix: Modify the property instead of reassigning the object.

Example 3: Array Reassignment

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

Example 4: Within a Function Scope

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

Example 5: In Loops

Fix: Use let for variables that change within loops.

Example 6: Constant Function Parameters

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

Example 7: Constants in Conditional Blocks

Fix: Use let if the variable needs to change.

Example 8: Reassigning Properties of a Constant Object

Fix: Modify only the properties of the object.

Strategies to Prevent Errors

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

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

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

Best Practices

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

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

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

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

Related Articles

March 13, 2024

Expressjs Error: 405 Method Not Allowed

March 11, 2024

Expressjs Error: 502 Bad Gateway

I’m here to assist you.

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

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Why am I getting "TypeError: Assignment to constant variable" when trying to import my function?

I am trying to import my function from utils/login.js file, in my login.js file I have this.

I also have a utils/index.js file with this in

when I run const {login} = require("./utils") from the terminal I get this error but I'm not sure how to resolve it

TypeError: Assignment to constant variable.

imlearningcode's user avatar

As the error suggests, seems like the constant login was already declared in your scope.

You have to rename the constant.

Shimon Brandsdorfer's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Apply for Swiss residence permit: some non-EU nationals related points
  • Does "my grades suffered" mean "my grades became worse" or "my grades were bad"?
  • How can I enable read only mode in microSD card
  • Tiny book about a planet full of man-eating sunflowers
  • HTTP: how likely are you to be compromised by using it just once?
  • Definition of "Supports DSP" or "has DSP extensions" in a processor
  • Who is a "sibling"?
  • What are some plausible means for increasing the atmospheric pressure on a post-apocalyptic earth?
  • Personal Loan to a Friend
  • If a reference is no longer publicly available, should you include the proofs of the results you cite from it?
  • A TCP server which uses one thread to read while writing data with another thread
  • Is there some sort of kitchen utensil/device like a cylinder with a strainer?
  • How to turn a desert into a fertile farmland with engineering?
  • C# Linked List implementation
  • Voronoi mesh of a circular image
  • What is the safest way to camp in a zombie apocalypse?
  • A Colorful explosion
  • Sink vs Basin distinction
  • Comprehensive Guide to saying Mourners' Kaddish
  • What is the purpose of the M1 pin on a Z80
  • if people are bred like dogs, what can be achieved?
  • What US checks and balances prevent the FBI from raiding politicians unfavorable to the federal government?
  • Designing Optocoupler circuit
  • Clear jel to thicken the filling of a key lime pie?

assignment to constant variable. js

COMMENTS

  1. TypeError: Assignment to constant variable

    Or given you don't really need to reassign it, just create the variable inside the body if the if statement: exports.show = function(req, res){. const username = req.params.username; const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'"; con.query(sql, function(err, result){.

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

  3. TypeError: Assignment to Constant Variable in JavaScript

    Learn why this error happens when using the `const` keyword and how to solve it with `let` or different variable names. Also, understand the difference between reassigning a variable and changing its values.

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

  5. const

    The const declaration creates an immutable 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. You should understand const declarations ...

  6. JavaScript const

    Constant Objects and Arrays. The keyword const is a little 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 ...

  7. TypeError: invalid assignment to const "x"

    A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword. Examples Invalid redeclaration. Assigning a value to the same constant name in the same block-scope will throw. const COLUMNS = 80

  8. 11 Variables and assignment

    Scope A is the (direct) scope of x.; Scopes B and C are inner scopes of scope A.; Scope A is an outer scope of scope B and scope C.; Each variable is accessible in its direct scope and all scopes nested within that scope. The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.. 11.4.1 Shadowing variables

  9. JavaScript const

    Learn about the powerful JavaScript const keyword. This tutorial will teach you all about the const keyword and how to use it in your JavaScript code. ... Assignment to constant variable. In this example, a constant named MAX_SIZE is declared and initialized with a value of 10. The constant is then used in a for loop to limit the number of ...

  10. JavaScript const: Declaring Constants in ES6

    ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. const CONSTANT_NAME = value; Code language: JavaScript (javascript) By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.

  11. JavaScript TypeError

    This JavaScript exception is read-only works in strict mode-only and It occurs if a global variable or object property which has assigned to a value, is a read-only property. Message: TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: "x" is read-only (Firefox) TypeError: 0 is read-only (Firefox) TypeError

  12. Declaring a Variable with const in JavaScript

    Uncaught TypeError: Assignment to constant variable. Declaring an Array using JavaScript's const Keyword. When you declare an array with the const keyword in JavaScript, you can still add, remove and change elements within the array. While you can change elements of an array, it is crucial to note that you still can't re-assign the variable.

  13. JavaScript Const

    This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. Message: TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclara

  14. JavaScript Variables and Constants

    JavaScript Constants. A constant is a type of variable whose value cannot be changed. In JavaScript, we use the const keyword to create constants. For example, // assign 5 to num const num = 5; Once a constant is initialized, we cannot change its value. // assign 5 to num const num = 5; // assign 10 to num.

  15. Constant Variables in JavaScript, or: When "const"

    In JavaScript, const does not mean constant, but one-time assignment. It's a subtle yet important distinction. Let's see what one-time assignment means: // We're declaring PI to be a constant variable. const PI = 3.141592653589793; // Any attempt to assign a new value to PI // fails because PI is a constant variable.

  16. javascript

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

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

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

  18. NodeJS TypeError: Assignment to Constant Variable

    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.

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

  20. Expressions and operators

    Evaluation example 1. y = x = f() is equivalent to y = (x = f()), because the assignment operator = is right-associative.However, it evaluates from left to right: The assignment expression y = x = f() starts to evaluate.. The y on this assignment's left-hand side evaluates into a reference to the variable named y.; The assignment expression x = f() starts to evaluate.

  21. three.js

    That happens because you are creating a folder constant when importing folder from ../js/first.js.You cannot reassign a value to any constant, including folder.Don't use == or ===, as those are comparasion operators and don't change the value of folder.. If you want to pass information from second.js to first.js, consider exporting a function from second.js.

  22. javascript

    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.