How do you use the ? : (conditional) operator in JavaScript?

前端 未结 18 1918
感动是毒
感动是毒 2020-11-21 05:48

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

18条回答
  •  生来不讨喜
    2020-11-21 06:17

    This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

      // var firstName = 'John'; // Undefined
      var lastName = 'Doe';
    
      // if lastName or firstName is undefined, false, null or empty => fallback to empty string
      lastName = lastName || '';
      firstName = firstName || '';
    
      var displayName = '';
    
      // if lastName (or firstName) is undefined, false, null or empty
      // displayName equals 'John' OR 'Doe'
    
      // if lastName and firstName are not empty
      // a space is inserted between the names
      displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;
    
    
      // if display name is undefined, false, null or empty => fallback to 'Unnamed'
      displayName = displayName || 'Unnamed';
    
      console.log(displayName);
    

    Ternary Operator

提交回复
热议问题