Reputation: 2345
I made a mistake in the code below. In a variable "x", I stored one character from a string "s". Then, I mistakenly incremented "x" which caused the error given after the code. Why does JS allow me to increment a character variable in the first place ? How do I prevent such errors from happening ?
function jsFun(s){
var x = s.charAt(0);
s++;//Wrong !
x = s.charAt(1);
return x;
}
console.log(jsFun("one"));
Error : In line 4.
TypeError: s.charAt is not a function
Upvotes: 0
Views: 2041
Reputation: 3752
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:
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.
Upvotes: 5
Reputation: 413
As some have mentioned JavaScript will let you do this because is weakly typed. Here is a good post about it - https://stackoverflow.com/a/964926/8161471
How can you prevent it? There are tools you can use like extensions with your editor that will highlight such problems as you work on your code. TypeScript, a superset of JavaScript, is another good alternative which can give you a more strongly type approach that looks a lot like C#/Java. What is TypeScript and why would I use it in place of JavaScript?.
Upvotes: 2