Can someone tell what does this ( _ )do (Java Script)

constructor(author) {
    this._author = author;
  }`

why did we use _ between this. and author ?

2 Likes

Technically, nothing. Underscores are no different from letters when naming identifiers.

In other languages, it’s a convention for naming class fields, to make it easier to distinguish between a field and regular variable inside a method. You don’t need to use the this keyword in other languages when accessing fields (unless its name conflicts with that of another variable), so fields can easily be mistaken for regular variables.

Correct me if I’m wrong, but I think it’s redundant for JavaScript, because you can’t access field names without using the this keyword anyway.

A situation where you might want to prefix a field name with an underscore is if your class happens happens to have getters or setters.
class Sample {
  constructor(author) {
    this._author = author;
  }

  get author() { // this.author refers to this getter
    return this._author;
  }
}
2 Likes

Hi @issamath ,
try this article that explain better what 's _ in Javascript:


Maybe this help you.

2 Likes