+ 4

const arr=["hello","world"]; for(let i=0;i<arr.length;i++) { const elem=arr[i]; console .log(elem ); } //hello //world?

As we know const values cannot be changed so in this example how the const elem store "hello" and then store "world"? Any explanation please?

27th Dec 2018, 8:15 AM
Hafsa Mohamed
Hafsa Mohamed - avatar
7 Respuestas
+ 4
The value of a constant cannot change through reassignment, and it can't be redeclared. But it can be assigned once only during declaration.
27th Dec 2018, 8:40 AM
Calviղ
Calviղ - avatar
+ 3
After thinking and searching i got the answer, but if one feeling confused like I was In JavaScript, const only means that the binding (the association between variable name and variable value) is immutable. The value itself may be mutable. In this example const elem=arr[i]; cannot equal to any other value but the value it self arr[i]; may be changed to different values.
27th Dec 2018, 9:30 AM
Hafsa Mohamed
Hafsa Mohamed - avatar
+ 3
Gordon I think constant equals to the looping of i so when i equals 1 it stores "one" and when i is not equal to 1 it stores "two"
27th Dec 2018, 9:49 AM
Hafsa Mohamed
Hafsa Mohamed - avatar
+ 1
Actually it's not reassignment const arr is declared once only. For const elem It is declared in the block scope of the for loop And garbage collector has collected the const elem for i ==0 And at i==1, There is no const elem yet. So we can declare const elem
27th Dec 2018, 9:08 AM
Gordon
Gordon - avatar
+ 1
Good that you searched. But no, you are not getting closer to the truth. arr[0] is fixed as "hello" and arr[1] is fixed as "world" To be more clear, I used "one" and "two" in this demo for you: https://code.sololearn.com/WGtvott81wbZ/?ref=app I hope the above demo wipes out your misunderstanding Can I know which reference site you are looking at? So I can point out how wrong that site is. A better resource is Mozilla document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const Quote: "Constants are block-scoped" When you run the for loop, for each i, it is a different block scope. So it may looks like that the constant is declared for more than one time. But actually in each block scope, it is declared once only.
27th Dec 2018, 9:36 AM
Gordon
Gordon - avatar
+ 1
Hafsa Hussein 1. You are absolutely correct regarding the ternary operator. 2. And from console log, you see the output is one two Isn't it? 3. That's because when my for loop runs, there are two i. 1 and 2. 4. In the block scope of i ==1, constant is declared and assigned for the first time as "one" 5. In the block scope of i==2, constant is declared and assigned, again the -->FIRST <-- time, as "two"
27th Dec 2018, 9:55 AM
Gordon
Gordon - avatar
0
Why do you delete the comment on my demo code. I typed a long reply and it is gone because you deleted your comment 😅
27th Dec 2018, 9:52 AM
Gordon
Gordon - avatar