Reputation: 845
This minor issue causes me 5 hours to fix. Finally I figured out. See this code:
<script language="JavaScript" type="text/javascript">
var x;
.... // a lot of codes here
var k=x.trim();
</script>
The above code made the whole app stop working!
I remembered that I used to do like that before but got no problem.
So, about var x; ... x.trim();
, Why sometimes it allows but sometimes it makes the rest of the code stop working?
And what is the best code practice for it?
Upvotes: 0
Views: 76
Reputation: 4512
You can do like this:
if(typeof x === 'undefined'){
// your get an error message
}
else
{
var k=x.toString().trim();
}
Using strict equality operator ===
above is good idea there because in JS, you can name a variable as undefined too:
var undefined = "something";
So using === makes sure that you are really checking against undefined value for a variable.
Upvotes: 1
Reputation: 8376
I would expand Rajesh's answer. He's right, when you try to call a method that does not exist, a TypeError is thrown. The easiest and fool-proof approach would be to use try/catch to ensure that the rest of the code would be executed as it should. But it's likely that even if it does, you don't get the result you want.
I believe the best way to do would be to wrap the value you're having into String object. It's as easy as
var k = String(x).trim();
It does several important things:
x
, whatever it be, into a string, i.e. when you check its type, it's always 'string'
and is always an instance of the String object.trim
which does what it should.There may be several pitfalls. If x
is undefined, null, NaN or an object, the result of String(x)
would be, correspondingly, 'undefined'
, 'null'
, 'NaN'
, or '[object Object]'
. If x
is an array, it's a specific case, and the value would be the same as if you call x.join(',')
, for example
x = [1, 2, 3];
var k = String(x).trim; // k is now '1,2,3'
So always keep in mind what types you're dealing with.
Just as with String, you can cast variables to other types, but naïvely converting anything into a Number, a String or an Array is considered a very bad practice. You should always be somewhat sure what type you're working with.
Upvotes: 0
Reputation: 24925
trim
is a function of String
. Refer MDN - String.trim().
So when you apply it to an integer, it fails and throws error, causing you code to stop work
try{
var a = 1;
console.log(a.trim());
}
catch(ex){
console.log(ex);
}
You can try to convert number to string using .toString()
and then apply .trim()
try{
var a = 1;
console.log(a.toString().trim());
}
catch(ex){
console.log(ex);
}
Upvotes: 0