4

I have read the lexical grammar of the String literals. I found out that both "\9" and "\7" are considered invalid string literals. But why does alert("\9") give 9 while alert("\7") is empty (I expected \7)?

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
user1039304
  • 365
  • 5
  • 10

2 Answers2

4

alert("\7") doesn't give you an empty string, it gives you a string with character 7. This is because the browser you're testing it on extends the definition of a string literal to allow for octal character escapes, as described in Section B.1.2 of the spec.

Since 9 isn't an octal digit, \9 doesn't get interpreted as an octal character escape sequence, and so the backslash is silently dropped.

Note that in a conforming implementation, if you were in strict mode, alert("\7") wouldn't work either, as you can see here with Chrome, Firefox, or another browser that supports strict mode: Live Copy | Source

(function() {
  "use strict";

  alert("\7"); // fails
})();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

\7 is interpreted as an octal string and yields a single character with ASCII value 7. 9 does not fit in the octal base, hence it is interpreted as a regular character. The backslash is silently dropped as it does not have any side-effects.

See also https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Using_special_characters_in_strings:

\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192