0

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?

2
  • 3
    % is not a valid identifier, it's the modulus operator. Commented Jul 7, 2021 at 21:27
  • % is not a valid identifier, so you can only access it using window['%']. Commented Jul 7, 2021 at 21:28

3 Answers 3

1

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.

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

Comments

1

% 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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.