What's the correct way to convert a potential undefined value to string in javascript?
- User
What's the correct way to convert a potential undefined value to string in javascript?
Assistant
In JavaScript, you can use the nullish coalescing operator (
??) along with theString()function to convert a potentially undefined value to a string. The nullish coalescing operator returns the left-hand side operand if it is not null or undefined, otherwise it returns the right-hand side operand.Here's an example:
const value = undefined; const strValue = String(value ?? 'default value'); console.log(strValue); // Output: 'default value'In this example, the
??operator checks ifvalueis null or undefined. Sincevalueisundefined, the operator uses the string'default value'instead, and theString()function converts it to a string.You can replace
'default value'with any default value you want to use in case the original value is null or undefined.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.