Michał Kozłowski 8b40da02a3 multiple ternary operator challenge - add note about code readability (#36269)
* fix multiple ternary operator challenge

* Fix a typo in multiple ternary operator challenger

Co-Authored-By: Parth Parth <34807532+thecodingaviator@users.noreply.github.com>

* Fix a typo in multiple ternary operator challenge #2

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2019-06-15 19:06:56 +01:00

2.6 KiB

id, title, challengeType, videoUrl
id title challengeType videoUrl
587d7b7e367417b2b2512b21 Use Multiple Conditional (Ternary) Operators 1 https://scrimba.com/c/cyWJBT4

Description

In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions. The following function uses if, else if, and else statements to check multiple conditions:
function findGreaterOrEqual(a, b) {
  if (a === b) {
    return "a and b are equal";
  }
  else if (a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}

The above function can be re-written using multiple conditional operators:

function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" 
    : (a > b) ? "a is greater" 
    : "b is greater";
}

However, this should be used with care as using multiple conditional operators without proper indentation may make your code hard to read. For example:

function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}

Instructions

Use multiple conditional operators in the checkSign function to check if a number is positive, negative or zero.

Tests

tests:
  - text: <code>checkSign</code> should use multiple <code>conditional operators</code>
    testString: assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code), '<code>checkSign</code> should use multiple <code>conditional operators</code>');
  - text: <code>checkSign(10)</code> should return "positive". Note that capitalization matters
    testString: assert(checkSign(10) === 'positive', '<code>checkSign(10)</code> should return "positive". Note that capitalization matters');
  - text: <code>checkSign(-12)</code> should return "negative". Note that capitalization matters
    testString: assert(checkSign(-12) === 'negative', '<code>checkSign(-12)</code> should return "negative". Note that capitalization matters');
  - text: <code>checkSign(0)</code> should return "zero". Note that capitalization matters
    testString: assert(checkSign(0) === 'zero', '<code>checkSign(0)</code> should return "zero". Note that capitalization matters');

Challenge Seed

function checkSign(num) {

}

checkSign(10);

Solution

function checkSign(num) {
  return (num > 0) ? 'positive' : (num < 0) ? 'negative' : 'zero';
}