0

Just wondering if it is valid to use $ in front of variable name in JavaScript (like PHP).

So can I do something like this:

var $x = 1; // Is this valid with the $ in front?
var y = 2; // This is valid JavaScript

I have tested a little and it seems to work, but want to make sure it is valid and will work across all browsers before I do it.

Flux
  • 9,805
  • 5
  • 46
  • 92
jsherk
  • 6,128
  • 8
  • 51
  • 83

4 Answers4

2

Javascript variable names can begin with a letter, $ or _ . As long as you dont start your variable name with a number, your good to go.

DpK
  • 100
  • 4
2

Valid, yes, but a code style not usually used unless it has meaning.

I've seen some folks use $someVar to indicate a jQuery-decorated element, for example. (Because, jQuery by default uses $ for its name.)

I would not recommend using it unless you have a specific reason, and are consistent in your codebase.

Brad
  • 159,648
  • 54
  • 349
  • 530
2

Yes, it has always been valid since the first edition of the ECMAScript language specification.

According to the 10th edition of the ECMAScript language specification published in 2019 (see: ECMAScript Language: Lexical Grammar - Names and Keywords), the grammar for variable names is:

IdentifierName::
  IdentifierStart
  IdentifierName IdentifierPart

IdentifierStart::
  UnicodeIDStart
  $
  _
  \ UnicodeEscapeSequence

IdentifierPart::
  UnicodeIDContinue
  $
  \ UnicodeEscapeSequence
  <ZWNJ>
  <ZWJ>

...

As you can see, it is valid to have $ anywhere in the variable name.

This has always been the case since the first edition of ECMAScript standard published in 1997. Section 4.5 Identifiers from the first edition says:

An identifier is a character sequence of unlimited length, where each character in the sequence must be a letter, a decimal digit, an underscore (_) character, or a dollar sign ($) character, and the first character may not be a decimal digit.

Flux
  • 9,805
  • 5
  • 46
  • 92
1

Yes, Javascript accepts $ and _ as variable names. It works and it is valid in any browser.Check it here