Categories
JavaScript Answers

How to replace undefined with a empty string with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *