RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

Is there some syntactic sugar I can use to set a JS variable to "" if it's null?

I want to set a variable to an empty string in Javascript, a pretty routine thing. I just don't know how to do it without doing this:

if (existingnote==null) {
  existingnote = "";
}

Is there a faster or easier way?

Upvotes: 2

Views: 973

Answers (3)

kennarddh
kennarddh

Reputation: 2665

There is now shorthand for @DaveNewton answer

Logical OR Assignment

let existingnote = null

existingnote || = "";

console.log(existingnote)

Upvotes: 0

ayanami
ayanami

Reputation: 1706

If you want just null to work this way, try

existingnote = (existingnote === null? "": existingnote);

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

existingnote = existingnote || "";

This checks for truthy/falsy, which may not be what you want.

Upvotes: 3

Related Questions