+ 1

What use do constants have?

so I was looking at some javascript docs and I found out about constants and what I got is that they are like variables but need a value assigned to them from the start and cannot be change(correct me if I am wrong). If that's right then why would you use one instead of a regular variable?

28th Sep 2017, 4:29 PM
PeterMx
PeterMx - avatar
5 odpowiedzi
+ 6
You already answered your question. You have a variable with a value that can't be changed, and that's why they're useful. For example, take something in life that is a constant, such as the math value of pi. You would make the pi variable a constant since its value is absolute and isn't something that'll change, ever. Then you can use this and not be concerned that something will change its value. Another example could be something simple like days in a week; it's always 7 (or whatever calendar system you use). So, can you do all of the same things with a regular variable? Of course. However, you have potential to accidentally change its value, and that wouldn't work out when you -know- you're dealing with something that has a constant value.
28th Sep 2017, 4:37 PM
AgentSmith
+ 3
More efficient and secure, yes. Being quite literal, it's not a variable since it doesn't change and its value is already known, so it's good to ensure that it can't be changed since it would cease to be what it actually is.
28th Sep 2017, 5:01 PM
AgentSmith
+ 1
so it's purpouse it's being more secure?
28th Sep 2017, 4:55 PM
PeterMx
PeterMx - avatar
+ 1
Not to mention the fact that constants can be placed into the hardware instructions by the compiler saving memory lookup during execution.
28th Sep 2017, 5:35 PM
John Wells
John Wells - avatar
+ 1
thank you, that's really useful info.
28th Sep 2017, 5:37 PM
PeterMx
PeterMx - avatar