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

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.

Время на прочтение
6 мин

Количество просмотров 29K

Источник картинки

Работающий код может иметь изъяны — например, быть недостаточно простым, лаконичным и понятным. Это может быть признаком более глубоких проблем в коде, а избавиться от них можно с помощью рефакторинга. В этой статье разберем наиболее популярные недостатки кода. Материал адаптирован на русский язык вместе с Глебом Михеевым, директором по технологиям Skillbox и спикером профессии «Frontend-разработчик PRO» и преподавателем курса Frontend-разработки в Skillbox Борзуновым Игорем.

Непонятный выбор имени

Код должен оставаться читаемым и удобным для всей команды. Для этого компании нужны единые принципы выбора имен переменных, методов, классов, констант и других единиц кода. Единая стратегия пригодится, когда команда начнет расти и сотрудникам придется говорить на одном языке. Если стратегии еще нет, то ее надо создать.

Общие принципы выбора имени:

  • Стратегия выбора последовательна.

  • Из имени понятно назначение переменной.

  • Имена легко различимы между собой.

  • Имя переменной можно произнести вслух.

  • Переменная должна легко искаться, а значит, в имени лучше не использовать популярные слова или буквы.

const a = 'Frontend course';

const b = 1;

const c = '100$'

Как вы можете наблюдать, подобный нейминг приводит простой код в непонятный набор символов, который работает неочевидно. Заменив нейминг, можно легко превратить данный код в самодокументирующуюся конструкцию

const courseName = 'Frontend course';

const courseId = 1;

const coursePrice = '100$'

Длинный метод

Метод, функция или процедура, которые занимают слишком много строк, — это источник ошибок. Понять работу такого кода становится сложно. Мы рекомендуем придерживаться принципа, по которому метод выполняет только одну задачу и выполняет ее хорошо.

async function makeAnOrder() {

  const form = document.querySelector<HTMLFormElement>('form#basket');

  const basket = new FormData(form);

  if (!basket.get('name')) {

      throw new Error('Вы не указали имя');

  }

  if (!basket.get('address')) {

      throw new Error('Вы не указали адрес доставки');

  }

  const user = await fetch('/api/user').then(results => results.json())

  basket.set('user_id', user.id);

  basket.set('discount', user.discount);

  fetch('/api/order', { method: 'POST', body: basket })

      .then(results => results.json())

      .then(() => {

          alert('Заказ удачно отправлен')

      })

}

Подобный код сочетает в себе смешанную логику всего действия. Если представить, что параметров в классе будет еще больше, с течение времени, такой код станет неподдерживаемым. 

Если воспользоваться принципом разделения ответственности, такой код станет читабельнее и разделит ответственность так, как это заложено логически.

async function makeAnOrder() {

  const basket = getBasket();

  vaildateBasket(basket);

  await applyDiscount(basket);

  createOrder(basket).then(() => {

    alert('Заказ удачно отправлен')

  })

}

function getBasket() {

  const form = document.querySelector('form#basket');

  return new FormData(form);

}

function vaildateBasket(basket) {

  if (!basket.get('name')) {

    throw new Error('Вы не указали имя');

  }

  if (!basket.get('address')) {

    throw new Error('Вы не указали адрес доставки');

  }

}

function createOrder(basket) {

  fetch('/api/order', { method: 'POST', body: basket })

    .then(results => results.json())

}

async function applyDiscount() {

  const user = await fetch('/api/user').then(results => results.json())

  basket.set('user_id', user.id);

  basket.set('discount', user.discount);

}

Объект бога

Объект кода, который хранит в себе слишком много составляющих программы и отвечает за слишком большое количество задач. Объект бога сложно поддерживать, при этом от него зависит работа всей программы.

Главный принцип хорошего кода — разделять большую задачу на маленькие функциональные части. Поэтому и объект бога лучше разделить на несколько небольших. Это поможет избежать ошибок, сократит время изучения кода и упростит тестирование.

Глеб Михеев: «Часто бывает такая ситуация: лаконичный код по ходу решения задачи обрастает дополнительной логикой. Например, функция записи начинает проверять загружаемый файл, права доступа к нему, конвертировать его в нужный формат, складывать в систему хранения, сбрасывать и прогревать кэш. 

Вместо лаконичных трех строчек выходит огромная функция с большой когнитивной сложностью. Ее прочтение занимает много времени, а корректировка грозит непредсказуемыми поломками. Все это усложняет поддержку кода. В результате его дороже обслуживать, как морально, так и с точки зрения прямой стоимости.

Вот почему важно не оставлять такой код как есть, а после разработки функционала проводить рефакторинг. Упрощать код логически, разнося на маленькие простые блоки, которые легко читать, изменять и тестировать».

Ситуация, при которой идентичный или очень похожий код повторяется в программе. Из-за существования дубликатов разработчикам становится сложнее вносить изменения, поскольку они вынуждены искать все повторы. Помимо этого, существование клонов снижает скорость работы программы и усложняет ее понимание.

Избавиться от дубликатов можно с помощью создания вспомогательного метода или класса, а также с помощью выражения одного клона через другой. Наличие дубликатов в исходном коде может указывать на более глубокие проблемы, например, неудачный выбор архитектуры.

let button = document.getElementById("button");

let anotherButton = document.getElementById("anotherButton");

button.onclick = function() {

    modal.style.display = "block";

    modal.style.height = "100%";

    modal.style.width = "50%";

    modal.style.position = "fixed";

}

anotherButton.onclick = function() {

    modal.style.display = "block";

    modal.style.height = "100%";

    modal.style.width = "50%";

    modal.style.position = "fixed";

}

Для того, чтобы избегать подобных казусов, следует пользоваться обобщенными конструкциями:

function showModal() {

  modal.style.display = "block";

  modal.style.display = "block";

  modal.style.height = "100%";

  modal.style.width = "50%";

  modal.style.position = "fixed";

}

button.onclick = showModal

anotherButton.onclick = showModal

Слишком много параметров

Большое число аргументов функции затрудняет чтение и тестирование кода. Разработчик Роберт Мартин в книге «Чистый код. Создание анализ и рефакторинг» назвал ноль идеальным числом параметров:

Глеб Михеев: «В идеальном случае количество аргументов функции равно нулю. Далее следуют функции с одним аргументом и с двумя аргументами. Функций с тремя аргументами следует по возможности избегать. Необходимость функций с большим количеством аргументов должна быть подкреплена очень вескими доводами».

Надуманная сложность

Код, в который ввели сложные шаблоны проектирования, в то время как с поставленной задачей справится и более простое решение. Такой код создают, стремясь упростить существующие решения, но достигают обратных результатов: код становится сложным и нечитаемым.

Введение сложных шаблонов проектирования не говорит о высоком уровне разработчика. Наоборот, это указывает на его незрелость: неумение упрощать и оценивать задачу целиком.

Стрельба дробью

Ситуация, когда для выполнения, казалось бы, простых задач вносят большое количество изменений в код. При этом сами изменения идентичны или очень похожи между собой. Это похоже на стрельбу по цели из дробовика вместо одного точного выстрела — отсюда и название. 

При рефакторинге повторяющийся код нужно свести к одному участку. Возможно, придется изменить саму архитектуру кода, которая привела к появлению таких решений. При написании программы разработчикам нужно иметь в виду, что код будет дорабатываться, а быстрое решение проблемы впоследствии может привести к «стрельбе дробью».

Мутации переменной

Это специфическая проблема JavaScript, которая указывает на изменения переменной. Но мутация отличается от изменения тем, что происходит непредсказуемо. Из-за изменения одной переменной в другом месте меняется и другая, связанная с ней.

Мутации приводят к ошибкам, которые сложно обнаружить, а поведение программы делают непредсказуемым. В идеале лучше избегать операций, подразумевающих мутацию, а если это невозможно, то мутацию следует делать как можно более явной и читаемой.

Хорошая практика в JavaScript — использование так называемого иммутабельного подхода: запрета мутирования переменных. Он позволяет избавиться от этой проблемы. Пример реализации –– библиотека

ImmutableJs

.

Если воспользоваться ключевым словом let, то значение переменной действительно можно переопределить 

let age = 25;

age = "Двадцать пять";

В случае с const, будет выведена ошибка, так как ключевое слово const неизменно в данном примере 

const age = 25;

age = 'Ягодка опять';

> Uncaught TypeError: Assignment to constant variable.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Assetto corsa ошибка 0xc000007b при запуске гонки
  • Assetto corsa competizione ошибка при запуске
  • Assertion failure ошибка
  • Assertion failed lightroom ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии