Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

JavaScript Data Type toString() Conundrum

markmmiller09
Kilo Expert

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;

  }

1 ACCEPTED SOLUTION

adiddigi
Tera Guru

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!




switch - JavaScript | MDN



Comparison operators - JavaScript | MDN


View solution in original post

2 REPLIES 2

adiddigi
Tera Guru

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!




switch - JavaScript | MDN



Comparison operators - JavaScript | MDN


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!