0

I know that underscore means private variable that used in C# and Java but my current project is in Typescript React so is using underscore in maybe function parameter recommended? Is it bad practice?

i.e

function(_a: any, _b: any, _orderBy: string) {
    if (_b[_orderBy] < _a[_orderBy])
        return -1;
    if (_b[_orderBy] > _a[_orderBy])
        return 1;
    return 0;
}
Mike S.
  • 3,050
  • 2
  • 9
  • 23
  • I think naming them `a` and `b` is bad practice, but why would using `_` be bad practice if it's a code conventon for you? – Mike S. Feb 24 '21 at 13:34
  • it's just an example. the main question I am asking is underscore :D – Altanbagana Feb 24 '21 at 13:36
  • Note that using an underscore prefix in C# is a *convention*, not something enforced by the compiler. I can declare a public property with an underscore prefix in C# and nothing happens: https://dotnetfiddle.net/tUkglR – Heretic Monkey Feb 24 '21 at 13:47

2 Answers2

1

From MDN:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (0–9).

Underscore i.e. _ has no special meaning in JavaScript. It is neither good nor bad practice. It is just a valid identifier character. And, it has nothing to do with TypeScript.

Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
  • 1
    I just thought my code would be more cleaner, easier to read with underscore. Thanks for the information :D – Altanbagana Feb 24 '21 at 13:40
  • @Altanbagana Yes, you can use it without any worry. `_` is no special. – Ajeet Shah Feb 24 '21 at 13:42
  • For those looking for Private Fields in JavaScript class, use `#`, e.g. [#privateField](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields). – Ajeet Shah Feb 24 '21 at 13:59
1

On February 21, TypeScript 3.8 has been released and now It supports the emerging private fields standard that’s bundled into ES10 and currently supported by Chrome and Opera.

So, if you are on Typescript >3.8, to make fields private, just give them a name starting with #.

Example: #x = 0;

Else, if you are on an older version on Typescript, you should have a look on this question, especially the answer.

More info about private fields on Typescript's documentation.

beeruot
  • 11
  • 3