What is the underscore "_" in JavaScript? [duplicate]

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?

1

3 Answers

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.

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.

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.

You Might Also Like