ternary statement code example

Example 1: if statement shorthand c

if (true)
	printf("This is the shorthand");

// OR

(true) ? (/*run if true*/) : (/*run if false*/);

Example 2: ternary operator

(condition) ? (if true, do this) : (otherwise, do this)

Example 3: ternary operator

// (condition) ? (if true, do this) : (otherwise, do this)
const hasAccount = true
// let userDisplayMessage
// if (hasAccount) {
//   userDisplayMessage = 'Welcome Back'
// } else {
//   userDisplayMessage = 'Please Sign Up'
// }
const userDisplayMessage = hasAccount ? 'Welcome Back' : 'Please Sign Up'
console.log(userDisplayMessage)

Example 4: javascript ternary operator

//ternary operator syntax and usage:
condition ? doThisIfTrue : doThisIfFalse

//Simple example:
let num1 = 1;
let num2 = 2;
num1 < num2 ? console.log("True") : console.log("False");
// => "True"

//Reverse it with greater than ( > ):
num1 > num2 ? console.log("True") : console.log("False");
// => "False"

Example 5: Ternary Operator

condition ? expression-if-true : expression-if-false;

function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater";
}

Example 6: javascript ternary

condition ? doThisIfTrue : doThisIfFalse

1 > 2 ? console.log(true) : console.log(false)
// returns false

Tags:

C Example