Added formatting and explanation to Use the Conditional (Ternary) Operator (#34310)
This commit is contained in:
committed by
Randell Dawson
parent
8679a70c55
commit
b10256e853
@ -1,38 +1,36 @@
|
||||
---
|
||||
title: Use the Conditional (Ternary) Operator
|
||||
---
|
||||
|
||||
 Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program  and write your own code 
|
||||
|
||||
## Use the Conditional (Ternary) Operator
|
||||
|
||||
### Problem explanation:
|
||||
_Use the `conditional operator` in the `checkEqual` function to check if two numbers are equal or not. The function should return either true or false._
|
||||
###  Problem Explanation:
|
||||
|
||||
* You need to write a function named `checkEqual`, which checks if the two parameters are equal.
|
||||
* If the parameters are equal, `true` is to be returned else `false` should be returned.
|
||||
|
||||
##  Hint
|
||||
|
||||
Use ternary operator to check for equality.
|
||||
|
||||
#### Hint 1
|
||||
Remember that the "traditional" `if...else` syntax can be re-written using the conditional operator (`condition ? statement if true : statement if false;`)
|
||||
> _try to solve the problem now_
|
||||
>
|
||||
|
||||
## Spoiler Alert!
|
||||
|
||||
## Spoiler alert!
|
||||

|
||||
|
||||
**Solution ahead!**
|
||||
|
||||
## Code solution:
|
||||
|
||||
```javascript
|
||||
function checkEqual(a, b) {
|
||||
return a === b ? true : false;
|
||||
}
|
||||
```
|
||||
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Ternary-operator).
|
||||
|
||||
### Code explanation
|
||||
- The function checks if the `condition` before the interrogation sign (`?`) is true, and if so, executes the `true` statement. Otherwise, it returns `false`.
|
||||
|
||||
|
||||
### Resources
|
||||
|
||||
- ["Conditional (ternary) operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)
|
||||
|
||||
|
||||
|
||||
### Code Explanation:
|
||||
|
||||
* A function `checkEqual` is declared, it accepts two parameters in variables `a` and `b`.
|
||||
* The `return` statement would return the value of the evaluated ternary expression.
|
||||
* The ternary expression checks if `a` and `b` are equal or not and returns `true` or `false` respectively.
|
||||
|
Reference in New Issue
Block a user