Because the ECMAScript Language Specification allows it https://www.ecma-international.org/ecma-262/5.1/#sec-11.4.4.
The only time the ++
unary operator would throw a SyntaxError is if all the following are true:
- Type(expr) is Reference is true
- IsStrictReference(expr) is true
- Type(GetBase(expr)) is Environment Record
- GetReferencedName(expr) is either "eval" or "arguments"
Otherwise, it will try to parse the value into a number and increase it by one. A string does not meet the throwing criteria, so it gets parsed to a number (resulting in NaN
in your example) and then, after increasing its value by 1, it still returns NaN
.
If the string was numeric such as "1234"
, you would see that it gets turned into a number and increased by one, as you would expect with a number. Once you try to call the charAt
function, however, your code would error out, since numbers do not have that function.
To prevent this behaviour using plain Javascript, you could check whether the variable is a non-NaN number before increasing it
if (!Number.isNaN(s)) {
s++
}
You could also use isNaN
if you would like to verify is the string is numeric-ish.
Also, like other answers said, you could use a type-checked alternative such as Typescript or a static type checker such as flow.js to prevent these errors at compile time.