ternary operator js code example

Example 1: if statement javascript one line ?

(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");

Example 2: js ternary

condition ? ifTrue : ifFalse

Example 3: javascript ternary

// example:
age >= 18 ? `wine` : `water`;

// syntax:
// <expression> ? <value-if-true> : <value-if-false>

Example 4: ternary function javascript

var variable;
if (condition)
  variable = "something";
else
  variable = "something else";

//is the same as:

var variable = condition ? "something" : "something else";

Example 5: javascript if shorthand

condition ? doThisIfTrue : doThisIfFalse

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

Example 6: ternary operator js

condition ? expression1 : expression2 
// Will return expression1 if condition = true and expression2 if condition != true

Tags: