Assignment to constant variable ошибка

Ошибка: createInteractionPanel.js:11 Uncaught TypeError: Assignment to constant variable.
at deleteNote (createInteractionPanel.js:11:21)
at HTMLImageElement. (createInteractionPanel.js:26:9)

Основной код:

import {activeNotesData} from "../../data/activeNotesData.js";

function findParentId(el) {
    return el.parentNode.id
}

function deleteNote(id) {
    activeNotesData = activeNotesData.filter(note => note.id !== id)
}

export const createInteractionPanel = (itemId) => {

    let interactionPanel = document.createElement("div");
    interactionPanel.setAttribute("id", itemId)


    let deleteIcon = document.createElement("img");
    deleteIcon.src = "images/garbageIcon.svg";
    deleteIcon.className = "note-interaction-icon";

    deleteIcon.addEventListener('click', function () {
        deleteNote(findParentId(this))
    });

    interactionPanel.appendChild(deleteIcon);

    return interactionPanel;
}

Создание объекта:

export let activeNotesData = [
    {
        id: 123,
        name: 'Shopping list',
        created: 'April 20, 2021',
        category: 'Quote',
        content: 'Tomatoes, bread',
        dates: ''
    },
    {
        id: Math.random() + Math.random(),
        name: 'The theory of evolution',
        created: 'April 27, 2021',
        category: 'Thought',
        content: 'The evolution The evolution The evolution',
        dates: ''
    },
    {
        id: Math.random() + Math.random(),
        name: 'New Feature',
        created: 'May 5, 2021',
        category: 'Idea',
        content: 'Implement new tomatoes, bread',
        dates: ['3/5/2021', '5/5/2021']
    }]

задан 3 апр 2022 в 15:51

kisa_2001's user avatar

В js нельзя напрямую изменять импортируемые переменные вне зависимости от способа их объявления (const или let). Однако, эти переменные можно изменять в самом модуле, который их экспортирует.

Подробное объяснение на английском

В данном случае, чтобы изменить activeNotesData, необходимо перенести функцию deleteNote из createInteractionPanel.js в activeNotesData.js (не забудьте добавить export), после чего импортировать её в createInteractionPanel.js вместе с activeNotesData.

P.S. Также, при фильтрации activeNotesData не забудьте привести note.id и id к одному типу, чтобы строгое неравенство note.id !== id работало как ожидается.
Я так понимаю, note.id у вас типа Number, а id, полученный с помощью функции findParentId, передается в функцию deleteNote с типом String.

ответ дан 3 апр 2022 в 17:34

NameDropper's user avatar

Table of Contents

  • Problem : TypeError: Assignment to constant variable
  • Solution : TypeError: Assignment to constant variable
    • Rename the variable
    • Change variable type to let or var
    • Check if scope is correct
  • const and immutability

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

Let’s see with the help of simple example.

const country1 = «India»;

// attempt to reassign const variable

country1= «china»;

console.log(country1);

Output

country= «china»;

       ^

TypeError: Assignment to constant variable.

    at Object.<anonymous> (HelloWorld.js:4:8)

    at Module._compile (internal/modules/cjs/loader.js:959:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)

    at Module.load (internal/modules/cjs/loader.js:815:32)

    at Function.Module._load (internal/modules/cjs/loader.js:727:14)

    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)

    at internal/main/run_main_module.js:17:11

Solution : TypeError: Assignment to constant variable

Rename the variable

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

const country1 = «India»;

const country2= «china»;

console.log(country1);

console.log(country2);

Change variable type to let or var

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

Change type to either let or var.

var country1 = «India»;

country1= «China»;

console.log(country1);

Output

Check if scope is correct

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

const country1 = «India»;

function countryName() {

const country1= «China»;

}

This is valid declaration as scope for country1 is different.

const and immutability

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

Let’s see with help of simple example:

const country = {

  name : ‘India’

}

country = {

  name : ‘Bhutan’

}

console.log(country);

Output

country = {

        ^

TypeError: Assignment to constant variable.

    at Object.<anonymous> (HelloWorld.js:5:9)

    at Module._compile (internal/modules/cjs/loader.js:959:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)

    at Module.load (internal/modules/cjs/loader.js:815:32)

    at Function.Module._load (internal/modules/cjs/loader.js:727:14)

    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)

    at internal/main/run_main_module.js:17:11

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

const country = {

  name : ‘India’

}

country.name = ‘Bhutan’

console.log(country);

Output

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

Александр Звягинцев

Добрый день.
Почему такое решение дает ошибку:

// BEGIN (write your solution here)
const finalGrade = (exam, projects) => {
if (exam > 90 || projects > 10) {
finalGrade= 100;
} else if (exam > 75 && projects >= 5) {
finalGrade= 90;
} else if (exam > 50 && projects >= 2) {
finalGrade= 75;
} else {
finalGrade= 0;
}
return finalGrade;
}
// END

А такое нет:

// BEGIN
const finalGrade = (exam, projects) => {
if (exam > 90 || projects > 10) {
return 100;
} else if (exam > 75 && projects >= 5) {
return 90;
} else if (exam > 50 && projects >= 2) {
return 75;
} else {
return 0;
}
};
// END

Я думал по сути это одно и тоже.


5


0

Александр О.

Почему такое решение дает ошибку:

Почему вы не приводите текст ошибки?


0

Александр Звягинцев

make: Entering directory ‘/usr/src/app’
jest —colors
FAIL tests/finalGrade.test.js
● finalGrade

TypeError: Assignment to constant variable.

  at finalGrade (finalGrade.js:4:16)
  at Object.<anonymous>.test (__tests__/finalGrade.test.js:4:35)
  at Promise.resolve.then.el (../../local/share/.config/yarn/global/node_modules/p-map/index.js:42:16)

✕ finalGrade (4ms)

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.824s
Ran all test suites.
Makefile:2: recipe for target ‘test’ failed
make: *** [test] Error 1
make: Leaving directory ‘/usr/src/app’


0

Александр О.

Хорошо, в сообщении об ошибке есть такая строчка: TypeError: Assignment to constant variable, говорящая о попытке присвоить значение существующей константе (константе, в отличии от переменной, можно присвоить значение всего один раз — при начальной инициализации (когда первый раз делаете присвоение const myConst = 12345;)).

Далее в сообщении об ошибке указывается место в программе, где ошибка была выявлена (это не обязательно точное место возникновения ошибки, но часто бывает именно так, уроки курса про ошибки ждут вас ещё впереди): finalGrade.js:4:16

Уже невооружённым взгядом видно, что вы сначала определяете функцию finalGrade, в теле этой функции вы зачем-то пытаетесь присвоить новое значение константе finalGrade. Но это не стоит делать, как минимум, по двум причинам: во-первых, это константа и новое значение ей присвоить не получится, а во-вторых, в эту константу вы записываете создаваемую в практике функцию — зачем в теле создаваемой функции пытаться перезаписать эту константу?


0


0

user-23344eb81f27d372

Александр О.,
Благодарю, с вашей помощью разобрался с подобной проблемой.


0

Don’t be confused when your program outputs the error line “TypeError: Assignment to the constant variable” in JavaScript because this error is not difficult to fix. In this article, I will give you some examples to help you understand why it occurs and then come up with the most reasonable way to fix it.

The “TypeError: Assignment to constant variable” in JavaScript occurs when you try to change the value of a variable declared with the keyword ‘const’ however, with an array or an object, you can change the elements of the parts for arrays and properties for objects when they are declared with the ‘const’ keyword.

The error message occurs as follows:

Uncaught TypeError: Assignment to constant variable

Example:

// For a standard variable
const str = "LearnShareIT";
str = "Hello LearnShareIT"; // Error

// For the variable is an array
const arr = [1, 2, 9, 2];
arr = [5, 7, 3]; // Error

// For the variable is an object
const obj = { property: "value" };
obj = { property: "value1" }; // Error

How to fix the “TypeError: Assignment to constant variable” in JavaScript?

For a standard variable

For a standard variable, we only have one way is that instead of using the keyword ‘const’, we can use the keyword ‘var’ or ‘let’ to declare it because if we want to change the value of the variable, we cannot use it. ‘const’ this will throw an error.

Example:

// For a normal variable
var str = "LearnShareIT";
str = "Hello LearnShareIT";

Your program will not get an error in this case because when you declare it with the keyword ‘var’ or you can declare a variable with the keyword ‘let’, the program will not throw this error.

Example:

// For a normal variable
let str = "LearnShareIT";
str = "Hello LearnShareIT";

For the variable is an array

For the variable is an array, you can use the wrong way to change the elements of the array. You cannot use an array variable created from ‘const’ to assign it to another array, but you can change the values of its elements by calling each element to change them.

Example:

// For the variable is an array
const arr = [1, 2, 9, 2];
arr[0] = 3;
arr[1] = 4;
arr[2] = 8;
arr[3] = 7;
arr = [5, 7, 3]; // Error

We cannot assign a declared array to another array. This will throw an error in your program so remember though you cannot assign to another array, you can change the value of its element, and don’t let your program throw this error again.

For the variable is an object

If we try to assign another object to an instance variable declared with ‘const’ but its properties are different, we can assign a different value to it without any error appearing.

Example:

// For the variable is an object
const obj = { property: "value" };
obj.property = "value1";
obj = { property: "value1" }; // Error

If we want our object to be assignable to another object, we can declare it with the ‘var’ or ‘let’ keyword then you can assign it to another object.

Summary

Through this article, please note that for variables declared with the keyword ‘const’, you cannot assign it with a similar value. We can only change the elements or properties of it in case the variable is an array or an object. Also, suppose the variable you create you want to assign or change its value. In that case, you should declare it with ‘var’ or ‘let’ to avoid encountering the correct “TypeError: Assignment to constant variable” in JavaScript. This article can help you, and your program. Wish you success!

Maybe you are interested:

  • TypeError: contains is not a function in JavaScript
  • TypeError: getMonth() is not a function in JavaScript
  • TypeError: date.getHours is not a function in JavaScript

Tom

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

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

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

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

First, let us know what this error means.

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

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

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

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

TypeError: Assignment to constant variable.

Here is an example code snippet that triggers the error:

const greeting = "Hello";
greeting = "Hi"; // This will trigger a Typeerror assignment to constant variable error

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

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

TypeError: Assignment to constant variable.

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

Let us explore more about how this error occurs.

How does Typeerror assignment to constant variable occurs?

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

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

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

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

TypeError: Assignment to constant variable.

This error can occur in various situations, such as:

  • Attempting to reassign a constant variable:

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

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

Here is an example:

const age = 30;
age = 35; // This will trigger a Typeerror assignment to constant variable error

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

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

TypeError: Assignment to constant variable.

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

  • Attempting to modify a constant object:

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

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

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

For example:

const person = {
  name: "John",
  age: 23
};
person.age = 24; // This will not trigger an error

person = {
  name: "gladyz",
  age: 24
}; // This will trigger a Typeerror assignment to constant variable error

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

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

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

  • Using strict mode:

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

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

Example:

"use strict";
const name = "John";
name = "Jane"; // This will trigger a Typeerror assignment to constant variable error

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

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

Now let’s fix this error.

Typeerror assignment to constant variable – Solutions

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

Solution 1: Declare the variable using the let or var keyword:

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

Just like the example below:

const age = 23;
let newAge = age + 1; // This will not trigger an error

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

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

For example:

const person = {
  name: "John",
  age: 30
};
person.age = 35; // This will not trigger an error

Solution 3: Declare the variable outside of strict mode:

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

"use strict";
let name = "John";
name = "Jane"; // This will not trigger an error

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

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

For example:

const name = 'John';
const newName = name + ' Paul';

console.log(newName); // Output: john Paul

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

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

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

For Example:

const name = 'John';

function updateName() {
  const name = 'Paul';
  console.log(name); // Output: Paul
}

updateName(); // Call the function
console.log(name); // Output: John

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

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

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

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

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

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

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

Conclusion

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

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

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

We’re happy to help you.

Happy coding! Have a Good day and God bless.

Понравилась статья? Поделить с друзьями:
  • Assassins creed syndicate ошибка msvcp110 dll
  • Assassins creed syndicate ошибка isdone dll
  • Assassins creed syndicate ошибка 0xc0000022
  • Assassins creed syndicate ошибка 0x60000001
  • Assassins creed syndicate код ошибки