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.

4
  • Ever seen jQuery? Commented Jun 14, 2020 at 4:01
  • If you're writing new code, consider const/let rather than var. Their scope is much more clear/less quirky. Commented Jun 14, 2020 at 4:03
  • Yes, it doesn't matter. This is an example you can refer: stackoverflow.com/q/43083577/1550476. Commented Jun 14, 2020 at 4:03
  • Sure, check official docs: ecma-international.org/ecma-262/10.0/… Commented Jun 14, 2020 at 4:09

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.