I already tried to search thoroughly, but I haven’t found the answer for Javascript.
So: I want to convert to strings (if not already) every JSON value sent to my API from the frontend in order to avoid triggering problems when processing the values.
To do so, I came with three methods:
- Use String(),
- Use variable + "",
The two ones above produce the same result.
Use .toString() This one is supposed to work as the ones above, converting any number, boolean, undefined or null into a string, but it is failing with null and undefined.
let data = { key1: 1, key2: "2", key3: false, key4: null, key5: undefined, key6: { subkey1: true } }; console.log("\nString() method:") for (let key in data) { let stringified = (String(data[key])) console.log(stringified) console.log(typeof(stringified)) } console.log("\nQuotes method:") for (let key in data) { let quotedValue = (data[key] + ""); console.log(quotedValue); console.log(typeof(quotedValue)); } console.log("\ntoString method:") for (let key in data) { let toStringTest = (data[key].toString()); console.log(toStringTest); console.log(typeof(toStringTest)); }
Which returns:
String() method:
1
string
2
string
false
string
null
string
undefined
string
[object Object]
string
Quotes method:
1
string
2
string
false
string
null
string
undefined
string
[object Object]
string
toString method:
1
string
2
string
false
string
Error: let toStringTest = (data[key].toString());
TypeError: Cannot read property 'toString' of null
While researching I believe I understood that toString() actually tries to “resolve” the value as if it was an expression or function. Is this accurate?