0

I know an if statement can easily accomplish this. I'm just wondering if there's anything that could be done even more simply.

For example:

var a
var b='this has a value'
var c = don't use a, instead use b
2
  • What exactly has to be true about a for you to not want to "use" it? Commented Nov 13, 2019 at 0:42
  • It was the simplest way to ask my question. It looks like @CertainPerformance has given me what I need. For more detail, I'm instantiating an IndexedDB database that may never have data in it, or not until later. When I load my page, I want it to check if there's data and populate an element with that data. If not, set the values temporarily until there is data. Commented Nov 13, 2019 at 0:45

1 Answer 1

4

If a, if defined, will be truthy, just alternate:

var c = a || b;

let a1;
let b1 = 5;
let c1 = a1 || b1;
console.log(c1);


let a2 = 'truthy';
let b2 = 10;
let c2 = a2 || b2;
console.log(c2);

Otherwise, if a can be defined but falsey, use the conditional operator:

var c = a !== undefined ? a : b;

let a1 = null;
let b1 = 5;
let c1 = a1 !== undefined ? a1 : b1;
console.log(c1);

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

2 Comments

in addition: let c = (typeof a === 'undefined') ? b : a;
Sure, if you're actually worried about there being an outer variable name called undefined, or about the global undefined property having been overwritten (in very ancient environments, pre-ES5), but those are very strange edge cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.