So I have this question about $ sign suffix naming convention in the RxJs code and Angular specifically. In angular best practices documentation and in the overall I have found that we should use it when declaring the Observable, but haven't seen using it with Subjects. Why ? I thought it should mean "asynchronous". Moreover Subjects are Observables. So they are async and you have to subscribe to them. For now I started using $ with Subjects too. Is any real con of this practice ?
-
8I for one don't tend to suffix subjects with it because almost always, the subjects are kept private. You then use the suffix on the public observable that you use to expose the subject. E.g. `public data$: Observable
= this.dataSubject.asObservable();` where `dataSubject` is private. – Octavian Mărculescu Nov 21 '21 at 09:17 -
This is just a habit to distinguish Observables from other variables. The current style guide https://angular.io/guide/styleguide doesn't mention this however. – martin Nov 21 '21 at 10:18
-
There is a naming convention hint regarding observables in the documentation of Angular: https://angular.io/guide/rx-library#naming-conventions-for-observables – Jonathan Stellwag Nov 22 '21 at 03:36
-
1Does this answer your question? [angular2 style guide - property with dollar sign?](https://stackoverflow.com/questions/37671700/angular2-style-guide-property-with-dollar-sign) – Jonathan Stellwag Nov 22 '21 at 03:37
3 Answers
On top of what Stoobish and Nipuna have said, I'd add that I like to have a $
as suffix as well to avoid ending up with a same variable name when working with an extracted value from a stream.
For example:
const currentTimeSeconds = currentTimeMs.pipe(
map(currentTimeMs => currentTimeMs * 1000)
)
In the example above you'd end up with 2 variables named currentTimeMs
. Sure that'd still work, but it's more confusing than helping. Sure you can rename the inner variable to something different as well. But overall I find it much clearer to have the following instead
const currentTimeSeconds$ = currentTimeMs$.pipe(
map(currentTimeMs => currentTimeMs * 1000)
)

- 22,502
- 10
- 80
- 121
$ suffix is used to indicate a certain variable is observable. it helps to distinguish between normal variables and observables. it's just a practice,
refer to this to see the official doc explaining the $ suffix. here

- 322
- 2
- 15
-
Style guide only mentions Observable type variables. What's your source for applying this to Subjects as well? – Samer Jun 26 '23 at 19:39
Every subject
is an observable
.
If you look at Angular docs:
This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to use the same name with or without the “$”.
The $ sign suffix doesn't mean asynchronous, its used as a soft convention to indicate that the variable is a stream. It is more like a naming helper to indicate types.

- 1,202
- 4
- 23