Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a variable to value if value is truthy

Is there a shorthand version of the following:

let myVar = "I contain a value!";

const myNewerVar = "I contain a newer value!";
if (myNewerVar) { 
    myVar = myNewerVar;
}

myVar should only be set if myNewerVar is truthy.

A shorter version of this is:

let myVar = "I contain a value!";

const myNewerVar = "I contain a newer value!";
if (myNewerVar) myVar = myNewerVar;

I don't like the repeated reading of myNewerVar, though.

Is there a way to simplify this even more?

like image 745
Oscar Avatar asked Dec 05 '25 13:12

Oscar


1 Answers

Yes, there is:

myVar = myNewerVar || myVar;
like image 131
Cristian Lupascu Avatar answered Dec 08 '25 03:12

Cristian Lupascu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!