1

The code I have returns a string:

return val ? val.name : "N/A";

But if the val.name returns "", it should return "N/A", not val.name. How to do that?

I tried

return val ? val.name === "" : "N/A";
return val.name ? val.name : "N/A";
etc.

But no luck yet.

AmazingDayToday
  • 3,724
  • 14
  • 35
  • 67
  • How would you write this as an `if` statement? The [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) is just shorthand – MTCoster Feb 19 '19 at 21:42
  • 2
    Possible duplicate of [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – Pedro leal Feb 19 '19 at 21:42

6 Answers6

5

Check whether val.name is truthy as well (an empty string is falsy), using the Boolean AND operator:

val && val.name ? val.name : "N/A"
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
5

const val = {
  name: ''
}

const a = val && val.name || "N/A";

console.log(a)
Taki
  • 17,320
  • 4
  • 26
  • 47
2
return (val || {}).name || 'N/A'
Tony Gentilcore
  • 193
  • 1
  • 11
1

I think what you need is a safe-read method for a property on an object. You can create a method that receives an object and a key and safe read that property chaining the verifications. Examples of chaining you can use to approach this are:

obj && obj.key ? obj.key : "N/A"

or

(obj || {}).key || "N/A"

or

obj && obj.key || "N/A"

And in some future (I hope not so long) maybe you can use next one:

obj?.key || "N/A"

Reference

Finally, a minimal example of a generic safe-read method could be:

let obj1 = null;
let obj2 = {};
let obj3 = {name: ""}
let obj4 = {name: "John"}

const safeReadObj = (obj, key) => obj && obj[key] || "N/A";

// Test cases:
console.log(safeReadObj(obj1, "name"));
console.log(safeReadObj(obj2, "name"));
console.log(safeReadObj(obj3, "name"));
console.log(safeReadObj(obj4, "name"));
Shidersz
  • 16,846
  • 2
  • 23
  • 48
0

This might help you to get Idea what you can do...

function getModify(string) {
    return (string=="")?('N/A'):(string);
}
console.log(getww(""));
console.log(getww("ub"));

// Output
// N/A
// ub
Ankit Agrawal
  • 596
  • 5
  • 12
0

return val.name != "" ? val.name : "N/A";

Cygital
  • 26
  • 5