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?
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