javascript question mark operator code example

Example 1: javascript question mark

//This is what is called a 'Conditional operator'
let result = condition ? value1 : value2
//               ^^        ^^      ^^
let result =  1 == 2   ?  "YES" : "NO!"
console.log(result)  //output: "NO!"

//Basically a short form of an if-else statment

Example 2: question mark and colon in javascript

const isBlack = false;const text = isBlack ? 'Yes, black!' : 'No, something else.';console.log(text);// "No, something else."

Example 3: ternary operator in javascript

FullName: (obj.FirstName && obj.LastName) ? obj.FirstName + " " + obj.LastName : "missing values",

Example 4: ternary operator javascript

condition ? exprIfTrue : exprIfFalse

//Example
let age = 26;
let beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

Example 5: question mark operator javascript

voteable = (age < 18) ? "Too young":"Old enough"
//         condition  ?   if true  :  if false

Tags:

Misc Example