2

This peice of code is really confusing me:

players = 5;
window["Kappa"] = 2;
if (players > 2)
  window["Kappa"] = 3;
document.write(Kappa);
document.write(Kappa);

As you can see it returns 23 even though it prints the same variable twice? Shouldn't it print 33 instead?

I get that window['variable'] creates a new variable called variable, but I still can't work out why the same variable would output different things... Why would they even use window instead of var here?

4
  • 2
    they aren’t the same identifier — they just look like they are: [ ...'Kappa' ].map(char => char.codePointAt(0)) // [8490, 97, 112, 112, 97] Commented Feb 24, 2017 at 18:59
  • I suggest you stop using global variables. Commented Feb 24, 2017 at 19:02
  • @AmericanSlime not my code :/ Commented Feb 24, 2017 at 19:03
  • those two Kappa's are not the same although they look like the same. when i copied the codes and posted into a file opened with vi and searched Kappa and only the Kappa assigned the value 2 were matched. Commented Feb 24, 2017 at 19:08

1 Answer 1

6

Explanation

The reason 23 is output instead of 33 is because there are actually 2 Kappa variables. One of the Kappa variables starts with a K (U+004B) however the other Kappa starts with a Kelvin K (U+212A). Even though they are different characters, the font renders them both in the same way.

Javascript Variables

Javascript variables can contain more than just ASCII characters. This site gives an explanation on the allowed characters:

An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or “Connector punctuation (Pc)”.

Javascript only looks at the character codes in the identifier, not at how the identifier is rendered. That's why these 2 variables are considered different by Javascript.

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

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.