To deal with null
or undefined
, use the String()
function to convert data to String.
String()
function always returns a string regardless of the value type.
The String()
function follows these rules:
toString()
method, it is called with no arguments and the result is returned. let value1 = 10; let value2 = true; let value3 = null; let value4; //from w w w. j a va 2 s . c om console.log(String(value1)); // "10" console.log(String(value2)); // "true" console.log(String(value3)); // "null" console.log(String(value4)); // "undefined"
Because toString()
isn't available on "null" and "undefined", the String()
method simply returns literal text for those values.