js if() shorthand code example

Example 1: shorthand if statment in js

isLoggedIn ? "Logout" : "Login";

Example 2: javascript if shorthand

condition ? doThisIfTrue : doThisIfFalse

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

Example 3: shorthand if statement js

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

// or

if (something)
  return;
// other code here

Example 4: shorthand if in javascript with return

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

Example 5: make shorter if statements with objects

var name_map = {
        "#first": "First Name",
        "#middle": "Middle Name",
        "#last": "Last Name"
}

if (Object.keys(check_map).every(selector => $(selector).val())) { 
	  // Yes, they all have non-blank values
} else {
	// No, at least one of them has a blank value (or didn't exist at all)
}