3

Easy question. Does exist something like php's ?? in javascript?

In php you can do condition ?? statement2

which is the same as condition? condition : statement2.

Is there something like that in javascript?

5
  • @JordanRunning similar answer, but not directly comparing PHP to JS Commented Jun 6, 2018 at 19:13
  • Good. || worked. Thanks Commented Jun 6, 2018 at 19:14
  • @ps2goat In PHP ?? is called the null coalescing operator. The linked question is "Null coalescing operator Javascript." It's literally the same question, and the accepted answer there answers OP's question exactly. Commented Jun 6, 2018 at 19:15
  • 1
    True, but people don't always know the official names of things, so that question may not show up in their search. Commented Jun 6, 2018 at 19:22
  • @ps2goat is right, That is why I asked Commented Jun 6, 2018 at 19:23

2 Answers 2

5

I would use the logical or operator (||)

console.log("true value" || "other")
console.log(false || "other")

This works because (source):

expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2

Sign up to request clarification or add additional context in comments.

Comments

0

So, if condition is false, go with statement2.

That's as simple as condition || statement2

If condition is truthy, if will be selected. If not, statement2 will be evaluated.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.