Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 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 Respostas
+ 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