McKayla
McKayla

Reputation: 6949

What is the hash character (#) used for in JavaScript?

I'm not talking about in the URL. I know what that does. I'm talking about how it's used in actual code.

After trying to assign it as a variable, I realized that it's reserved, but I don't know what for.

Upvotes: 2

Views: 4827

Answers (5)

thabs
thabs

Reputation: 613

An ongoing proposal (currently in stage 4) utilizes hashtags to mark fields as private. It is part of the ES2022 standard.

Example:

class Foo {
  x = 1; // public field
  #y = 2; // private field

  add() {
    return this.x + this.#y;
  }
}

Upvotes: 2

Surreal Dreams
Surreal Dreams

Reputation: 26380

In JavaScript variable names, no punctuation marks are permitted except for the underscore (_) and dollar sign ($). You can't start a variable name with a number, but otherwise all letters and numbers are permitted in a variable name.

So you can't have a variable name with # in it, no less a variable named #. It has no special meaning, it's just not permitted just as variable can't be named ~.

Upvotes: 0

Bart
Bart

Reputation: 27205

Javascript, or more precisely ECMAscript, is an evolving language. Some symbols and keywords (such as "class") have been reserved for future versions, even though they may not have any meaning at the moment.

Upvotes: 1

Chris
Chris

Reputation: 7855

I dont think, that this sign is somehow reserved fot another functionality. I found that rule here:

You must not use any punctuation marks of any kind in a JavaScript variable name, other than the underscore; for example... some:thing or big# or do'to would all be illegal.

This ist just, that javascript does not accept punctation signs in variable names ant due to this not parsing variables named like this as variables.

Upvotes: 1

Related Questions