2018-10-10 18:03:03 -04:00
---
id: 587d7b7e367417b2b2512b24
2021-02-06 04:42:36 +00:00
title: Use the Conditional (Ternary) Operator
2018-10-10 18:03:03 -04:00
challengeType: 1
2020-04-29 18:29:13 +08:00
forumTopicId: 301181
2021-01-13 03:31:00 +01:00
dashedName: use-the-conditional-ternary-operator
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2021-02-06 04:42:36 +00:00
The < dfn > conditional operator< / dfn > , also called the < dfn > ternary operator< / dfn > , can be used as a one line if-else expression.
2020-12-16 00:37:30 -07:00
2021-02-06 04:42:36 +00:00
The syntax is:
2020-12-16 00:37:30 -07:00
2021-02-06 04:42:36 +00:00
`condition ? expression-if-true : expression-if-false;`
2020-12-16 00:37:30 -07:00
2021-02-06 04:42:36 +00:00
The following function uses an if-else statement to check a condition:
2020-04-29 18:29:13 +08:00
```js
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
```
2021-02-06 04:42:36 +00:00
This can be re-written using the `conditional operator` :
2020-04-29 18:29:13 +08:00
```js
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}
```
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Use the `conditional operator` in the `checkEqual` function to check if two numbers are equal or not. The function should return either "Equal" or "Not Equal".
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`checkEqual` should use the `conditional operator`
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
`checkEqual(1, 2)` should return "Not Equal"
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert(checkEqual(1, 2) === 'Not Equal');
```
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`checkEqual(1, 1)` should return "Equal"
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert(checkEqual(1, 1) === 'Equal');
```
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`checkEqual(1, -1)` should return "Not Equal"
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(checkEqual(1, -1) === 'Not Equal');
2018-10-10 18:03:03 -04:00
```
2020-04-29 18:29:13 +08:00
2021-01-13 03:31:00 +01:00
# --seed--
## --seed-contents--
```js
function checkEqual(a, b) {
}
checkEqual(1, 2);
```
2020-12-16 00:37:30 -07:00
# --solutions--
2021-01-13 03:31:00 +01:00
```js
function checkEqual(a, b) {
return a === b ? "Equal" : "Not Equal";
}
```