shorthand ternary operator javascript code example

Example 1: shorthand if statment in js

isLoggedIn ? "Logout" : "Login";

Example 2: js ternary

condition ? ifTrue : ifFalse

Example 3: javascript ternary operator

//ternary operator example:
var isOpen = true; //try changing isOpen to false
var welcomeMessage  = isOpen ? "We are open, come on in." : "Sorry, we are closed.";

Example 4: 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 5: if shorthand typescript

const answer = x > 10 ? "greater than 10" : "less than 10";

Example 6: ternary operator javascript

// Write your function here:

const lifePhase = (age) => {
  return age < 0 || age > 140 ? 'This is not a valid age':
   age < 3  ? 'baby':
   age < 13 ? 'child':
   age < 20 ? 'teen':
   age < 65 ? 'adult':'senior citizen';
}




 console.log(lifePhase(5))

Tags:

Php Example