Sometimes, we want to replace undefined with a empty string with JavaScript.
In this article, we’ll look at how to replace undefined with a empty string with JavaScript.
How to replace undefined with a empty string with JavaScript?
To replace undefined with a empty string with JavaScript, we can use the || operator to return a default if its left operand is undefined.
For instance, we write:
const s = undefined
const newS = s || 'hello'
console.log(newS)
We assign newS to s is s is truthy or 'hello' otherwise.
Since s is undefined, which is falsy, newSis‘hello’`.
Conclusion
To replace undefined with a empty string with JavaScript, we can use the || operator to return a default if its left operand is undefined.