35

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,615
  • 6
  • 26
  • 50

3 Answers3

57

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
  • 758
  • 2
  • 10
  • 24
Daniel
  • 7,684
  • 7
  • 52
  • 76
13

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
  • 15,342
  • 3
  • 54
  • 62
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
  • 11,584
  • 5
  • 52
  • 78