Why Is My Variable Not Declaring In JavaScript

if we write:
window['anime'] = 'one punch man'

then we can access simply by:
console.log(anime)

but if we do:
window['%'] = 'symbol'

then this gives a syntax error:
console.log(%)

why is this happening?

Upvotes: 0

Views: 134

Answers (3)

Nick Maniutin
Nick Maniutin

Reputation: 11

% is being used in JS as a remainder operator and for that reason cannot be used as a variable name or to access values.

This article provides more info as to what can or can't be used as a variable name in JS: https://mathiasbynens.be/notes/javascript-identifiers-es6

Upvotes: 1

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

In JavaScript you can't declare a variable name as % since it can contain only letters, digits, underscores and dollar signs (but it can't begin with a digit).

So, when you do window['anime'] = 'one punch man', a global anime variable will be automatically created.
But, when you do window['%'] = 'symbol', it won't happen the same for %, since it doesn't follow the aforementioned rules.

Upvotes: 0

user16165663
user16165663

Reputation:

Give this a quick read through (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types), it is about JavaScript valid identifiers. Essentially, % is not a valid one, hence the error.

You could do window['percent'], window['PERCENT'], window['_PERCENT'], window['$percent'], etc. As long as you conform to the rules.

From the website:

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

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

Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) as well as "a" through "z" (lowercase).

You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers. (For more details, see this blog post.) You can also use the Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, $credit, and _name.

Upvotes: 1

Related Questions