[Guide] Basic JS: Ternary operator. Fixes and enhancements (#22633)
1. Fix code solution (it used the assignment operator to compare _a_ and _b_ instead of the comparison one; which wouldn't pass the test at the exercise page). 2. Add problem explanation, hint, code explanation, run example and resources
This commit is contained in:
committed by
Huyen Nguyen
parent
e4ae577cd9
commit
82459dad13
@ -3,15 +3,36 @@ title: Use the Conditional (Ternary) Operator
|
|||||||
---
|
---
|
||||||
## Use the Conditional (Ternary) Operator
|
## Use the Conditional (Ternary) Operator
|
||||||
|
|
||||||
### Hint 1
|
### Problem explanation:
|
||||||
Use ternary operator to check for equality.
|
_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._
|
||||||
|
|
||||||
### Warning Solution Ahead!!!
|
#### 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!
|
||||||
|
|
||||||
|
**Solution ahead!**
|
||||||
|
|
||||||
|
## Code solution:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
function checkEqual(a, b) {
|
function checkEqual(a, b) {
|
||||||
return (a == b ? true : false );
|
return a === b ? true : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
checkEqual(1, 2);
|
|
||||||
```
|
```
|
||||||
|
· 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)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user