[TypeScript/Angular] const variable name uppercase or lowercase?
There is no style guide for const in TypeScript or Angular official websites . This article will not say, you should always follow this guideline, but we should know general rule of thumb of const so as not to surprise other developers to some extend. In the end, it’s always best following the codebase.
Constants are block-scoped, much like variables declared using the
letkeyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). However, if a constant is an object or array its properties or items can be updated or removed.
This is very important part. It’s MUTABLE. This is where the convention of naming const is coming from (will be explained in detail below). As a result of lengthy article, the outcome will be like below.
const + UPPER_SNAKE_CASE = value cannot be reassigned, changed, but immutable (value type — number, string, boolean)
const + camelCase = value cannot be reassigned, but can be mutable. (reference type — object, array)
Let’s talk about const being mutable. SURPRISE! You can change change values for an object and array just like below.
Value type is basically immutable and reference type is mutable. What happens when you first assign the value in the memory (I don’t want to talk about memory in detail but it’s directly related ) is, if the variable is value type, it will be saved in Stack; if reference type, memory address is stored in Stack as a pointer to the actual value being stored in Heap. Now, can you think of something?
Yes, UPPER_SNAKE_CASE is happening for value type because you can’t really change the value of the value type just like Constant in statically typed languages . The reason is because if you assign a new value to const variable, you are completely creating a new value and store in Stack. If you change the value of the array and object, the address stays the same, but the value itself in the Heap will be changed, which means you are not completely creating a new object as you are creating a bunch of addresses pointing the same or changed value in Heap.
Let’s talk about reassignment. Reassignment means that you can’t use a assignment operator ( = ) again after an initial assignment.
const + UPPER_SNAKE_CASE = for magic values such as number or string
const + camelCase = object or array
But follow the codebase. Hey TypeScript, please make a guideline for naming.