var input = prompt('Jak się nazywasz?', '');
console.log('Cześć, ' + (input || 'żabko')); // ciekawe użycie operatora sumy. Pokazuje pierwszą wartość, która jest prawdą.
// operator || (OR) - jeśli pierwsza wartość nie jest prawdą, pokazuje drugą.
true || 'coś'; //true
// operator && (AND) - jeśli pierwsza jest prawdą, pokazuje drugą.
true && 'coś'; //'coś'
//wartości logiczne zamiast warunku IF
var foo = 10;
foo === 10 && doSomething(); // is the same thing as if (foo === 10) doSomething();
foo === 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
//ugly
function isAdult(age) {
if (age && age > 17) {
return true;
} else {
return false;
}
}
// nice
function isAdult(age) {
return age && age > 17; // true if both conditions meet
}
// ugly
if (userName) {
logIn (userName);
} else {
signUp ();
}
// nice
userName && logIn(userName) || signUp;
// ugly
var userID;
if (userName && userName.loggedIn) {
userID = userName.id;
} else {
userID = null;
}
// nicer
userName && userName.loggedIn ? userID = userName.id : userID = null
// more nice
var userID = userName && userName.loggedIn ? userName.id : null
// weird but looking even nicer -> przykład ektremalny
var userID = userName && userName.loggedIn && userName.id || null