javascriptsyntaxsimplify

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?


Solution

  • Yes, there is:

    myVar = myNewerVar || myVar;