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 thetoString()method 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 = value ?? "defaultValue"; const stringValue = strValue.toString(); console.log(stringValue); // Output: "defaultValue"In this example, if
valueis undefined, the??operator will return . Then, the method converts the value to a string.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.