Here’s what I’m trying to run:
if (z.le.zstart) then
if (y.ge.((6.95*wg_y2)/5)).and.(y.le.((12.55*wg_y2)/5)) then
indexmedia=nd
end if
end if
For context,
zstart
is an arbitrary line of constant y
.
wg_y2 = 5e-6
And for some reason it doesn’t like the (y.ge.((6.95*wg_y2)/5))
bit, as the (1) was placed at the end of that bit.
I had a suspicion that it doesn’t like anything that isn’t an integer in the if statement but I changed 6.95 to 7 and 12.55 to 13 and it still didn’t like it. Perhaps it needs to end up resolving to an integer?
I need these parameters to end up to
6.95 < y < 12.55 though.
Is there a workaround for this?
albert
7,8633 gold badges18 silver badges32 bronze badges
asked Jul 6, 2018 at 18:54
0
When compiling the code (not nice as I didn’t declare the variables!, but that isn’t the problem here so I abstain from it to keep it a bit small):
program tst
if (z.le.zstart) then
if (y.ge.((6.95*wg_y2)/5)).and.(y.le.((12.55*wg_y2)/5)) then
indexmedia=nd
end if
end if
end
one gets the error:
aa.f90:3:29:
if (y.ge.((6.95*wg_y2)/5)).and.(y.le.((12.55*wg_y2)/5)) then
1
Error: Cannot assign to a named constant at (1)
aa.f90:6:3:
end if
1
Error: Expecting END PROGRAM statement at (1)
This is due to a missing pair of round brackets in the line:
if (y.ge.((6.95*wg_y2)/5)).and.(y.le.((12.55*wg_y2)/5)) then
which should read
if ((y.ge.((6.95*wg_y2)/5)).and.(y.le.((12.55*wg_y2)/5))) then
answered Jul 7, 2018 at 9:23
albertalbert
7,8633 gold badges18 silver badges32 bronze badges
You should upgrade or use an alternative browser.
-
Forums
-
Other Sciences
-
Programming and Computer Science
Won’t Compile the simplest of programs! Am I being stupid?
-
Thread starter
JamesWMH -
Start date
Dec 2, 2010
- Dec 2, 2010
- #1
Hi, I’m just getting my teeth back into Fortran 90 I had a course on it last year, and just want to familirise myself with it before I apply for post grad stuff.
Anyway, the program i have written is:
program emosix
real:: a, roota
write(*,*) ‘Type an interger to find the square root (must be a positive number)’
read(*,*) a
if(a>=0.0)
stop
roota = sqrt(a)
write(*,*) ‘The sqaure root of ‘, a, ‘ = ‘, roota
pause
end program emosix
and I get the error code:
Error: Cannot assign to a named constant at (1)
C:UsersJamesDocumentsProgrammingEmo6~emo6.f90:15.5:
pause
1
Warning: Deleted feature: PAUSE statement at (1)
The warning about deleted feature hasn’t made any difference in the past, so I don’t think its that, but I have no idea what the cannot assign… part means?? Any ideas?
Thanks Jim
Answers and Replies
- Dec 2, 2010
- #2
Why is that stop in there after the if statement?
Also, your if statement needs an end if, I believe.
program emosix
real:: a, roota
write(*,*) 'Type an interger to find the square root (must be a positive number)'
read(*,*) a
if(a>=0.0) then
roota = sqrt(a)
write(*,*) 'The sqaure root of ', a, ' = ', roota
pause
end if
stop
end program emosix
- Dec 2, 2010
- #3
Hi
Thanks for the response, its in there to stop the program if the user puts a negative number in, as you can’t have a square root of negative number.
I put in the end if and it gives me another error
if(a>=0.0)
1
Error: Cannot assign to a named constant at (1)
C:UsersJamesDocumentsProgrammingEmo6~emo6.f90:11.3:
end if
1
Error: Expecting END PROGRAM statement at (1)
C:UsersJamesDocumentsProgrammingEmo6~emo6.f90:17.5:
pause
1
Warning: Deleted feature: PAUSE statement at (1)
that is what I get now.
- Dec 2, 2010
- #4
oops its supposed to be ‘a<=0.0’ but that didn’t change anything.
Thanks
Jim
- Dec 3, 2010
- #5
HiThanks for the response, its in there to stop the program if the user puts a negative number in, as you can’t have a square root of negative number.
Well, you can, but the result won’t be real. Instead of stopping the program, you should have logic that prevents the program from attempting to take the square root of a negative number.
I put in the end if and it gives me another errorif(a>=0.0)
1
Error: Cannot assign to a named constant at (1)
C:UsersJamesDocumentsProgrammingEmo6~emo6.f90:11.3:end if
1
Error: Expecting END PROGRAM statement at (1)
C:UsersJamesDocumentsProgrammingEmo6~emo6.f90:17.5:pause
1
Warning: Deleted feature: PAUSE statement at (1)that is what I get now.
oops its supposed to be ‘a<=0.0’ but that didn’t change anything.
You can take the square root of 0, so you should make the test expression a < 0.0.
As far as the «can’t assign to a named constant» business, try using a different variable for roota.
What does your code look like now? You if statement wasn’t formed correctly before, and it still might not be right.
- Dec 3, 2010
-
- #6
You need a «then». For example (also fixing your test condition):
if (a <= 0.0) then
stop
end if
For some reason, the missing «then» triggers the «can’t assign to a named constant» error.
- Dec 3, 2010
- #7
I added one in the code I showed in post #2, but didn’t say that explicitly. I should have, since the OP seems to have missed it.
For example (also fixing your test condition):if (a <= 0.0) then stop end if
For some reason, the missing «then» triggers the «can’t assign to a named constant» error.
The condition can be written as a < 0.0.
- Sep 24, 2011
- #8
suggestion of mark is absolutely correct
the error is coming due to absence of THEN statement
thanx
- Sep 25, 2011
- #9
I know this is an old thread that’s been bumped for some reason, but I would like to add one more thing.
The Fortran «if» statement doesn’t require a «then» (or an «endif» either) when the «if» is only controlling a single statement.
In this sense the OP’s code should (almost) have worked correctly, had he not put the «new line» after the «if» statement (since end of line is more than just white space in Fortran source code).
This should have worked correctly without «then» and without «endif»
Suggested for: Won’t Compile the simplest of programs! Am I being stupid?
- Last Post
- Dec 12, 2022
- Last Post
- Jul 30, 2022
- Last Post
- Jul 29, 2020
- Last Post
- May 24, 2022
- Last Post
- Apr 20, 2022
- Last Post
- Jun 11, 2022
- Last Post
- Jun 4, 2022
- Last Post
- Jun 14, 2022
- Last Post
- Jan 17, 2022
- Last Post
- Nov 10, 2021
-
Forums
-
Other Sciences
-
Programming and Computer Science
Description
Sergio Losilla
2014-02-11 13:29:09 UTC
Compiler version: GNU Fortran (Ubuntu 20130917-1ubuntu1) 4.9.0 20130917 (experimental) [trunk revision 202647] Test program: -------------------- program ifelif if (.TRUE.) else if (.FALSE.) end if end program -------------------- Error messages: ---------------------- if.F90:2.15: if (.TRUE.) 1 Error: Cannot assign to a named constant at (1) if.F90:3.11: else if (.FALSE.) 1 Error: Unexpected junk after ELSE statement at (1) [...] ---------------------- Both errors should read something like "Missing THEN after IF/ELSE IF". The first error message doesn't even make sense...
Comment 1
kargl
2014-02-11 14:35:07 UTC
(In reply to Sergio Losilla from comment #0)
> Compiler version:
> GNU Fortran (Ubuntu 20130917-1ubuntu1) 4.9.0 20130917 (experimental) [trunk
> revision 202647]
>
> Test program:
> --------------------
> program ifelif
> if (.TRUE.)
> else if (.FALSE.)
> end if
> end program
> --------------------
>
> Error messages:
> ----------------------
> if.F90:2.15:
>
> if (.TRUE.)
> 1
> Error: Cannot assign to a named constant at (1)
> if.F90:3.11:
>
> else if (.FALSE.)
> 1
> Error: Unexpected junk after ELSE statement at (1)
> [...]
> ----------------------
>
> Both errors should read something like "Missing THEN after IF/ELSE IF".
>
> The first error message doesn't even make sense...
How is the compiler suppose to know that the programmer may have
meant
program ifelif
if (.TRUE.) i = 42
if (.FALSE.) then
j = 42
end if
end program
As for the message that you think makes no sense, I suspect
the parse has identified (.TRUE.) as a malformed expression.
Comment 2
Sergio Losilla
2014-02-11 14:50:18 UTC
(In reply to kargl from comment #1) > How is the compiler suppose to know that the programmer may have > meant > > program ifelif > if (.TRUE.) i = 42 > if (.FALSE.) then > j = 42 > end if > end program As far as I know, there are two possible statements starting with if: if (<expr>) then if (<expr>) <statement> The compiler should recognize that *something* is missing, be it either a then or a statement. > As for the message that you think makes no sense, I suspect > the parse has identified (.TRUE.) as a malformed expression. Well, the message objectively makes no sense because there is no assignment whatsoever. At the very least, the message is confusing.
Comment 3
Dominique d’Humieres
2014-02-11 18:30:59 UTC
Confirmed on 4.7.4, 4.8.3, and trunk (4.9). Related to pr32151.
Comment 4
Dominique d’Humieres
2016-02-25 13:57:56 UTC
*** Bug 38303 has been marked as a duplicate of this bug. ***
Comment 5
Dominique d’Humieres
2019-02-02 19:32:42 UTC
> Error messages: > ---------------------- > if.F90:2.15: > > if (.TRUE.) > 1 > Error: Cannot assign to a named constant at (1) > if.F90:3.11: > > else if (.FALSE.) > 1 > Error: Unexpected junk after ELSE statement at (1) > [...] > ---------------------- > > Both errors should read something like "Missing THEN after IF/ELSE IF". > > The first error message doesn't even make sense... % gfc dec_type_print_red.f90 dec_type_print_red.f90:20:11: 20 | if (b) type*,a(i) ! test TYPE as PRINT inside one-line IF | 1 Error: Cannot assign to a named constant at (1) (from gfortran.dg/dec_type_print.f90 compiled without the -fdec option). IMO replacing "Cannot assign to a named constant" with "Syntax error" will give an immediate clue of what is wrong. A longer alternative could be something such as ""Syntax error, missing or bad STATEMENT".
Comment 6
Dominique d’Humieres
2019-02-19 13:10:55 UTC
I don't understand the goal of the block (line 1651 of gcc/fortran/match.c) /* The gfc_match_assignment() above may have returned a MATCH_NO where the assignment was to a named constant. Check that special case here. */ m = gfc_match_assignment (); if (m == MATCH_NO) { gfc_error ("Cannot assign to a named constant at %C"); gfc_free_expr (expr); gfc_undo_symbols (); gfc_current_locus = old_loc; return MATCH_ERROR; } The closest test matching my understanding of the comment is integer, parameter :: i = 1 if (i == 2) i = 3 ! { dg-error "in variable definition context" } end which gives the following error if_param.f90:2:12: 2 | if (i == 2) i = 3 ! { dg-error "in variable definition context" } | 1 Error: Named constant 'i' in variable definition context (assignment) at (1) If I remove the block, I get the following errors for the test in comment 0: pr60144.f90:2:15: 2 | if (.TRUE.) | 1 Error: Unclassifiable statement in IF-clause at (1) pr60144.f90:3:11: 3 | else if (.FALSE.) | 1 Error: Unexpected junk after ELSE statement at (1) which looks better for the IF statement. For the ELSE IF error, how can I move the caret after '(.FALSE.)' and replace 'junk' with something neutral (token, statement, ...)?
Comment 7
dominiq
2019-05-01 17:40:58 UTC
Author: dominiq Date: Wed May 1 17:40:22 2019 New Revision: 270776 URL: https://gcc.gnu.org/viewcvs?rev=270776&root=gcc&view=rev Log: 2019-05-01 Dominique d'Humieres <dominiq@gcc.gnu.org> PR fortran/60144 * match.c (gfc_match_parens): Change the location for missing ')'. (gfc_match_if): Detect a missing '('. Remove the spurious named constant error. Change the wording of some errors. (gfc_match_else): Change the wording of an error. (gfc_match_elseif): Detect a missing '('. Improve the matching process to get a better syntax analysis. PR fortran/60144 * gfortran.dg/block_name_2.f90: Adjust dg-error. * gfortran.dg/dec_type_print_3.f90.f90: Likewise * gfortran.dg/pr60144.f90: New test. Added: trunk/gcc/testsuite/gfortran.dg/pr60144.f90 Modified: trunk/gcc/fortran/ChangeLog trunk/gcc/fortran/match.c trunk/gcc/testsuite/ChangeLog trunk/gcc/testsuite/gfortran.dg/block_name_2.f90 trunk/gcc/testsuite/gfortran.dg/dec_type_print_3.f90
Comment 8
Dominique d’Humieres
2020-07-30 15:01:33 UTC
This is fixed since at least GCC7.
I have a fortran program that I am trying to compile. when I use the command
Code:
marge.f:61.11: * ST1=ST+1,ST2=ST+ST,SE=SD+2,SF=SU+SU+SU+SU+2) 1 Error: Parameter 'sust1' at (1) has not been declared or is a variable, which does not reduce to a constant expression marge.f:67.21: PARAMETER(SAa=SA,SSs=SS,SUu=SU,SDd=SD,S11=S1,SEe=SE) 1 Error: Parameter 'sa' at (1) has not been declared or is a variable, which does not reduce to a constant expression marge.f:104.19: WRITE (*,*) 'for axisymmetric, randomly-oriented, homogeneous par 1 Error: Unterminated character constant beginning at (1) marge.f:157.19: WRITE (*,*) 'Please refer to subroutine TNATURAL for more informa 1 Error: Unterminated character constant beginning at (1) marge.f:159.19: WRITE (*,*) 'Enter value for KReq (Re=equal-volume-sphere radius) 1 Error: Unterminated character constant beginning at (1) marge.f:162.19: WRITE (*,*) 'Please refer to subroutine TNATURAL for more informa 1 Error: Unterminated character constant beginning at (1) marge.f:252.72: BX1(N,N1+1,M+N2MAX+1)=BX1(N,N1+1,M+N2MAX+1)+CGN(M-IAM1+1)*AX1(N, 1 Error: Expected array subscript at (1) marge.f:253.72: BX2(N,N1+1,M+N2MAX+1)=BX2(N,N1+1,M+N2MAX+1)+CGN(M-IAM1+1)*AX2(N, 1 Error: Expected array subscript at (1) marge.f:266.72: if(BX1(N,N1+1,M+N2MAX+1).ne.0.and.BX1(NSO,N1+1,M+N2MAX+1).ne.0) 1 Error: Cannot assign to a named constant at (1) marge.f:269.12: end if 1 Error: Expecting END DO statement at (1) marge.f:270.72: if(BX2(N,N1+1,M+N2MAX+1).ne.0.and.BX2(NSO,N1+1,M+N2MAX+1).ne.0) 1 Error: Cannot assign to a named constant at (1) marge.f:273.12: end if 1 Error: Expecting END DO statement at (1) marge.f:281.72: if(BX1(N,N1+1,M+N2MAX+1).ne.0.and.BX1(NSO,N1+1,2-M+N2MAX+1).ne.0 1 Error: Syntax error in IF-expression at (1) marge.f:284.11: end if 1 Error: Expecting END DO statement at (1) marge.f:500.19: WRITE (*,*) 'Want Mueller matrix data stored in file? (1=yes, 0=n 1 Error: Unterminated character constant beginning at (1) marge.f:510.19: WRITE (*,*) 'Mueller matrix elements stored on files mm1.dat, mm2 1 Error: Unterminated character constant beginning at (1) marge.f:84.29: complex*16 G3(SDd),G4(SDd),G5(SDd) 1 Error: Variable 'sdd' cannot appear in the expression at (1) marge.f:84.33: complex*16 G3(SDd),G4(SDd),G5(SDd) 1 Error: The module or main program array 'g4' at (1) must have constant shape marge.f:76.17: real*8 A1(SAa),A2(SAa),A3(SAa),A4(SAa),B1(SAa),B2(SAa),ANG(SAa) 1 Error: Variable 'saa' cannot appear in the expression at (1) marge.f:76.21: real*8 A1(SAa),A2(SAa),A3(SAa),A4(SAa),B1(SAa),B2(SAa),ANG(SAa) 1 Error: The module or main program array 'a1' at (1) must have constant shape marge.f:75.36: real*8 AE1(SAa),AE2(SAa),AE3(SAa),AE4(SAa),BE1(SAa),BE2(SAa) 1 Error: Variable 'saa' cannot appear in the expression at (1) marge.f:75.40: real*8 AE1(SAa),AE2(SAa),AE3(SAa),AE4(SAa),BE1(SAa),BE2(SAa) 1 Error: The module or main program array 'ae3' at (1) must have constant shape marge.f:75.18: real*8 AE1(SAa),AE2(SAa),AE3(SAa),AE4(SAa),BE1(SAa),BE2(SAa) 1 Error: Variable 'saa' cannot appear in the expression at (1) marge.f:75.22: real*8 AE1(SAa),AE2(SAa),AE3(SAa),AE4(SAa),BE1(SAa),BE2(SAa) 1 Error: The module or main program array 'ae1' at (1) must have constant shape marge.f:76.41: real*8 A1(SAa),A2(SAa),A3(SAa),A4(SAa),B1(SAa),B2(SAa),ANG(SAa) 1 Error: Variable 'saa' cannot appear in the expression at (1) Fatal Error: Error count reached limit of 25.
Code:
marge.f:1: C ARTURO QUIRANTES SIERRA 1 Error: Unclassifiable statement at (1) marge.f:2: C Department of Applied Physics, Faculty of Sciences 1 Error: Unclassifiable statement at (1) marge.f:3: C University of Granada, 18071 Granada (SPAIN) 1 Error: Unclassifiable statement at (1) marge.f:4: C http://www.ugr.es/local/aquiran/codigos.htm 1 Error: Unclassifiable statement at (1) marge.f:5: C aquiran@ugr.es 1 Error: Unclassifiable statement at (1) marge.f:6: C 1 Error: Unclassifiable statement at (1) marge.f:7: C Last update: 20 september 2007 1 Error: Unclassifiable statement at (1) marge.f:8: C 1 Error: Unclassifiable statement at (1) marge.f:9: C This is MARGE, a computer code to calculate light-scattering properties 1 Error: Unclassifiable statement at (1) marge.f:10: C for randomly-oriented, homogeneous nonspherical scatterers 1 Error: Unclassifiable statement at (1) marge.f:11: C It is based on a T-matrix code, combined with Mishchenko's 1 Error: Unclassifiable statement at (1) marge.f:12: C orientation averaging scheme: JOSA A 8, 871-882 (1991) 1 Error: Unclassifiable statement at (1) marge.f:13: C 1 Error: Unclassifiable statement at (1) marge.f:14: C This code is made available on the following conditions: 1 Error: Unclassifiable statement at (1) marge.f:15: C 1 Error: Unclassifiable statement at (1) marge.f:16: C - You can use and modify it, as long as acknowledgment is given 1 Error: Unclassifiable statement at (1) marge.f:17: C to the author (that's me). I'd appreciate a reprint or e-copy 1 Error: Unclassifiable statement at (1) marge.f:18: C of any paper where my code has been used. 1 Error: Unclassifiable statement at (1) marge.f:19: C 1 Error: Unclassifiable statement at (1) marge.f:20: C - You can not sell it or use it in any way to get money out of it 1 Error: Unclassifiable statement at (1) marge.f:21: C (save for the research grants you might get thanks to it :) 1 Error: Unclassifiable statement at (1) marge.f:22: C 1 Error: Unclassifiable statement at (1) marge.f:23: C - I'm making this code available to the best of my knowledge. 1 Error: Unclassifiable statement at (1) marge.f:24: C It has been tested as throughly as possible, but bugs may remain 1 Error: Unclassifiable statement at (1) marge.f:25: C and overflow errors, particularly for large sizes and/or extreme 1 Error: Unclassifiable statement at (1) Fatal Error: Error count reached limit of 25.
Александр Звягинцев
Добрый день.
Почему такое решение дает ошибку:
// 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
У меня сложилось впечатление, что определения макросов в стиле C работают в gfortran?
#define ERROR_CHECKER(msg,stat)
IF (stat.NE.0) THEN
DO i = 1,BIG
IF(msg(i).NE.C_NULL_CHAR)THEN
ErrMsg(i:i) = msg(i)
ELSE
EXIT
END IF
END DO
IF(stat.EQ.1) THEN
ErrStat = ID_Warn
ELSE
ErrStat = ID_Fatal
RETURN
END IF
END IF
Но затем эта ошибка портит мне день:
IF (stat.NE.0) THEN DO i = 1,BIG IF(message
1
Error: Cannot assign to a named constant at (1)
Есть идеи, что я здесь делаю неправильно?
Второй вопрос: распознает ли Intel fortran макросы c-style? Если да, нужны ли флаги компилятора?
2 ответа
Лучший ответ
Вместо использования макроса просто преобразуйте макрос в функцию. Таким образом, у вас не будет большой зависимости от компилятора Fortran, имеющего возможность макроса.
LOGICAL FUNCTION ERROR_CHECKER(msg,stat)
character*(*) msg(*)
integer stat
IF (stat.NE.0) THEN
DO i = 1,BIG
IF(msg(i).NE.C_NULL_CHAR)THEN
ErrMsg(i:i) = msg(i)
ELSE
EXIT
END IF
END DO
IF(stat.EQ.1) THEN
ErrStat = ID_Warn
ELSE
ErrStat = ID_Fatal
RETURN .FALSE.
END IF
END IF
RETURN .TRUE.
END FUNCTION
В вашем коде
IF (ERROR_CHECKER(msg, stat)) RETURN
Изменить: в некоторых более поздних версиях Fortran есть разделители операторов (;), которые можно использовать. К сожалению, длина строки ограничена, поэтому ваш макрос не может быть очень длинным и содержать более одной управляющей структуры.
1
cup
23 Янв 2016 в 10:08
Помимо того факта, что такой подход к макросам не является хорошим стилем, вам не хватает необходимых разрывов строк в сгенерированном коде. Это можно исправить, поставив точку с запятой перед каждой обратной косой чертой в определении макроса (кроме первой строки).
0
Raul Laasner
4 Апр 2015 в 13:57
The JavaScript exception «invalid assignment to const» occurs when it was attempted to
alter a constant value. JavaScript
const
declarations can’t be re-assigned or redeclared.
Message
TypeError: Assignment to constant variable. (V8-based) TypeError: invalid assignment to const 'x' (Firefox) TypeError: Attempted to assign to readonly property. (Safari)
Error type
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.
Examples
Invalid redeclaration
Assigning a value to the same constant name in the same block-scope will throw.
const COLUMNS = 80;
// …
COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'
Fixing the error
There are multiple options to fix this error. Check what was intended to be achieved
with the constant in question.
Rename
If you meant to declare another constant, pick another name and re-name. This constant
name is already taken in this scope.
const COLUMNS = 80;
const WIDE_COLUMNS = 120;
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
.
let columns = 80;
// …
columns = 120;
Scoping
Check if you are in the correct scope. Should this constant appear in this scope or was
it meant to appear in a function, for example?
const COLUMNS = 80;
function setupBigScreenEnvironment() {
const COLUMNS = 120;
}
const and immutability
The const
declaration creates a read-only reference to a value. It does
not mean the value it holds is immutable, just that the variable
identifier cannot be reassigned. For instance, in case the content is an object, this
means the object itself can still be altered. This means that you can’t mutate the value
stored in a variable:
const obj = { foo: "bar" };
obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'
But you can mutate the properties in a variable:
obj.foo = "baz";
obj; // { foo: "baz" }