- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-05-2014 10:53 AM
Why, in JavaScript, must you force a variable to a string using .toString() when the value is already stored as a string?
The following switch statement ONLY worked when I explicitly assigned the variable to a string data type using toString()... Why is this!? The u_data_status is already a string...
var u_data_status = g_form.getValue('u_data_status').toString();
switch(u_data_status){
case 'New':
g_form.showFieldMsg('u_data_status','Field 1','info');
break;
case 'Additional Info Needed':
g_form.showFieldMsg('u_data_status','Field 2','info');
break;
case 'Pending':
g_form.showFieldMsg('u_data_status','Field 3','info');
break;
default:
g_form.showFieldMsg('u_data_status','Field 4','info');
break;
}
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-05-2014 12:59 PM
That's because g_form.getValue() returns an 'object', and that's why you will need to first type cast it to String using either toString() or appending an empty string.
and a Switch Javascript statement will do a Strict Comparison, which means it also checks the data type. So in your example when you just compare it to g_form.getValue() you will be strict comparing a String to an Object. Which is of course false.
But if you use a
if( g_form.getValue('something') == 'something else') {
}
notice the use of '==' which isn't strict comparision. '==' operator would typecast the object into a string, and so all works well!
Comparison operators - JavaScript | MDN
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-05-2014 12:59 PM
That's because g_form.getValue() returns an 'object', and that's why you will need to first type cast it to String using either toString() or appending an empty string.
and a Switch Javascript statement will do a Strict Comparison, which means it also checks the data type. So in your example when you just compare it to g_form.getValue() you will be strict comparing a String to an Object. Which is of course false.
But if you use a
if( g_form.getValue('something') == 'something else') {
}
notice the use of '==' which isn't strict comparision. '==' operator would typecast the object into a string, and so all works well!
Comparison operators - JavaScript | MDN
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-06-2014 06:15 AM
Awesome, thanks Abhiram! I was originally using if statements with the '==' operator which worked fine but I wanted to try a switch statement and was getting hung up on that . Again, thanks for the detailed response and the MDN links!