+ 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?
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.
+ 12
👍You are welcome friend! 😄
I hope it helped you.😉
+ 9
Danijel Ivanović Thank you!
+ 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.
+ 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.
+ 5
Exactly which aspect of the object is constant seems to vary from one language to another, which adds to the confusion.
+ 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
+ 3
So rather a Java kind of const instead of a C kind of const?
+ 3
Constant is fix does not change
- 1
qraulgo