27

I'm doing a redux tutorial, and I saw a call like this:

this._render();

and it's defined elsewhere as:

_render() {
    ....
} 

What is the underscore "_"? Why is it used?

userden
  • 1,441
  • 4
  • 24
  • 45

3 Answers3

41

This is convention of private methods and variables. In JavaScript there is no real privacy of classes.

It means that you should not use these method (starting with "_") out of your object. Of course technically you can, but "_" means that you should not.

Borjovsky
  • 626
  • 2
  • 10
  • 23
Daniel
  • 6,020
  • 5
  • 38
  • 65
9

Underscore (_) is just a plain valid character for variable/function name, it does not bring any additional feature.

However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.

shaochuancs
  • 13,987
  • 3
  • 48
  • 56
3

The underscore is simply a valid character in an identifier, so the method's name is _render.

It's a common pattern in languages without access modifiers to use underscores to denote private methods. In a language such as C#, which does have access modifiers, I could define a method as:

private void Foo() {}

The method Foo can then only be called from within the class which defined it.

In JavaScript you can't do this, so it's a typical design pattern to prefix the method with _ to show that it should be treated as private.

this._foo();

You can still call this method, it's just not considered good practice to do it outside of the class definition.

Aaron Christiansen
  • 10,601
  • 4
  • 49
  • 72