ternary operator javascript html code example
Example 1: js ternary
condition ? ifTrue : ifFalse
Example 2: javascript ternary
// example:
age >= 18 ? `wine` : `water`;
// syntax:
// <expression> ? <value-if-true> : <value-if-false>
Example 3: ternary operator shorthand javascript
let startingNum = startingNum ? otherNum : 1
// can be expressed as
let startingNum = otherNum || 1
// Another scenario not covered here is if you want the value
// to return false when not matched.
//The JavaScript shorthandfor this is:
let startingNum = startingNum ? otherNum : 0
// But it can be expressed as
let startingNum = startingNum && otherNum
Example 4: ternary operator javascript
// ternary operators are frequently used as a shorter cleaner if statement
// condition ? exprIfTrue : exprIfFalse
let age = 15;
let canDrive = age >= 16 ? 'yes' : 'no';
// canDrive will be 'no'
// the condition will be age > 16 which is false so canDrive will equal exprIfFalse
// this ternary is the same as this if else statement
let age = 15;
let canDrive;
if (age >= 16) {
canDrive = 'yes';
} else {
canDrive = 'no';
}
// canDrive will be 'no' because 15 is less than 16
Example 5: using ternary operator in javascript
// program to check pass or fail
let marks = prompt('Enter your marks :');
// check the condition
let result = (marks >= 40) ? 'pass' : 'fail';
console.log(`You ${result} the exam.`);