2018-09-30 23:01:58 +01:00
---
id: 587d7b7e367417b2b2512b24
title: Use the Conditional (Ternary) Operator
challengeType: 1
2019-08-05 09:17:33 -07:00
forumTopicId: 301181
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
The < dfn > conditional operator< / dfn > , also called the < dfn > ternary operator< / dfn > , can be used as a one line if-else expression.
The syntax is:
< code > condition ? statement-if-true : statement-if-false;< / code >
The following function uses an if-else statement to check a condition:
2019-05-17 06:20:30 -07:00
```js
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
```
2018-09-30 23:01:58 +01:00
This can be re-written using the < code > conditional operator< / code > :
2019-05-17 06:20:30 -07:00
```js
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}
```
2018-09-30 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
2018-12-03 08:49:57 +00:00
Use the < code > conditional operator< / code > in the < code > checkEqual< / code > function to check if two numbers are equal or not. The function should return either "Equal" or "Not Equal".
2018-09-30 23:01:58 +01:00
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
- text: < code > checkEqual</ code > should use the < code > conditional operator</ code >
2019-07-13 00:07:53 -07:00
testString: assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
2018-12-03 08:49:57 +00:00
- text: < code > checkEqual(1, 2)</ code > should return "Not Equal"
2019-07-13 00:07:53 -07:00
testString: assert(checkEqual(1, 2) === "Not Equal");
2018-12-03 08:49:57 +00:00
- text: < code > checkEqual(1, 1)</ code > should return "Equal"
2019-07-13 00:07:53 -07:00
testString: assert(checkEqual(1, 1) === "Equal");
2018-12-03 08:49:57 +00:00
- text: < code > checkEqual(1, -1)</ code > should return "Not Equal"
2019-07-13 00:07:53 -07:00
testString: assert(checkEqual(1, -1) === "Not Equal");
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
function checkEqual(a, b) {
2018-10-08 01:01:53 +01:00
2018-09-30 23:01:58 +01:00
}
checkEqual(1, 2);
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
2018-10-16 05:11:38 +05:30
function checkEqual(a, b) {
2018-12-03 08:49:57 +00:00
return a === b ? "Equal" : "Not Equal";
2018-10-16 05:11:38 +05:30
}
2018-09-30 23:01:58 +01:00
```
2019-07-18 08:24:12 -07:00
2018-09-30 23:01:58 +01:00
< / section >