15

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,223
  • 3
  • 19
  • 41

3 Answers3

24

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
  • 556
  • 2
  • 7
  • 21
Daniel
  • 5,039
  • 2
  • 28
  • 53
4

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
  • 12,430
  • 3
  • 40
  • 51
1

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
  • 9,515
  • 4
  • 44
  • 66