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