About an const | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 14

About an const

const arr=[1,2,3] arr[0]=5 Q: arr[0]=? Answer is 5... Found in a challenge. Why is the answer 5 and not 1? I thought const is used to declare something that cannot be changed...am I wrong?

12th Mar 2019, 9:23 AM
๐Ÿ‡ Alex Tuศ™inean ๐Ÿ’œ
๐Ÿ‡ Alex Tuศ™inean ๐Ÿ’œ - avatar
10 Answers
+ 13
๐Ÿ’งAlex Tusinean๐Ÿ”ฅ, DEEPAK โ€ข 'const' stands for constant, it is very similar to 'let'. The only differences are its value cannot be changed and it needs to be initialized where you are declaring it. const x = 13; console.log(x); // will print 13 x = 14 // will throw an error โžž Itโ€™s not that in the case of 'const' objects you can change the property of that objectโ€Š-โ€Šitโ€™s just that you canโ€™t reassign a 'const' variable. const obj = { ย ย ย  firstName: "Danijel", ย ย ย  lastName: "Ivanovic" }; console.log(obj); // will print the obj object obj.firstName = "@Dan&Jel"; console.log(obj); // will print the obj object, it has new firstName Note: you have to initialize a 'const' variable, you canโ€™t keep it uninitialized.
13th Mar 2019, 6:24 PM
Danijel Ivanoviฤ‡
Danijel Ivanoviฤ‡ - avatar
+ 12
๐Ÿ‘You are welcome friend! ๐Ÿ˜„ I hope it helped you.๐Ÿ˜‰
13th Mar 2019, 6:32 PM
Danijel Ivanoviฤ‡
Danijel Ivanoviฤ‡ - avatar
+ 9
13th Mar 2019, 6:30 PM
๐Ÿ‡ Alex Tuศ™inean ๐Ÿ’œ
๐Ÿ‡ Alex Tuศ™inean ๐Ÿ’œ - avatar
+ 6
When you're adding to an array or object you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to.
12th Mar 2019, 12:03 PM
M Maaz Azhar
M Maaz Azhar - avatar
+ 5
Maybe const prevents you from changing the object alright. Thus you can't now do const arr=[3, 2, 1]; But you can modify. I think this is because all JS cares is if you modify the id of the object not its value.
12th Mar 2019, 9:32 AM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 5
Exactly which aspect of the object is constant seems to vary from one language to another, which adds to the confusion.
14th Mar 2019, 3:02 AM
Sonic
Sonic - avatar
+ 4
Adding to Danijel Ivanoviฤ‡ I have a detailed blog post on const, let and var variable declarations in javascript, right here on sololearn. check it out! https://code.sololearn.com/WdauYjg8rOiF/?ref=app
14th Mar 2019, 6:07 AM
Benneth Yankey
Benneth Yankey - avatar
+ 3
So rather a Java kind of const instead of a C kind of const?
12th Mar 2019, 9:51 AM
HonFu
HonFu - avatar
+ 3
Constant is fix does not change
13th Mar 2019, 2:00 AM
DEEPAK
DEEPAK - avatar
- 1
qraulgo
12th Mar 2019, 9:02 PM
Abidk Haldar
Abidk Haldar - avatar