if (true) prn('hooray, I always print, because true is always true'); if (false) prn("nuts, I'll never print because false is never true"); if (1 === 1) prn('yes, I will print'); if (1002 === 1001) prn('nope, I will not print');
if (true) prn('always here'); else prn('never here'); if (false) prn('never here'); else prn('always here'); if (1 === 1) prn('yep (1===1) is true'); else prn('Never here'); if (1002 === 1001) prn('nope, (1002===1001) is false'); else prn('yep');
let payRate, isWeekend, isHoliday; //job doubles pay for weekend //triples for holiday //how do I apply? isWeekend = true; isHoliday = true; payRate = 15; if (isWeekend) payRate = payRate * 2; if (isHoliday) payRate = payRate * 3; prn('pay rate: ' + payRate);
let isWoman, title, greeting; const name = 'Lee'; //greet a woman isWoman = true; //ternary operator title = isWoman ? 'Ms.' : 'Mr.'; greeting = title + ' ' + name; prn(greeting); //greet a man isWoman = false; //ternary operator title = isWoman ? 'Ms.' : 'Mr.'; greeting = title + ' ' + name; prn(greeting);
let foo, boo; prn('Expecting: 10'); //option #1 -- null guard using nullish coalescing operator //quite simply, if foo is null/undefined we default to 10 boo = foo ?? 10; prn(`boo via nullish coalescing operator: ${boo}`); //option #1B -- null guard using logical OR operator //like option #1 except uses second value if first is falsy. //option #1 is better but B has better browswer support (needs polyfill) boo = foo || 10; prn(`boo via logical OR: ${boo}`); //option #2 -- null guard using our friend ternary boo = (foo != null) ? foo : 10; prn(`boo via ternary: ${boo}`); //option #3 -- null guard using old fashioned if-else //we use loose comparison "!=" which matches undefined and null if (foo != null) { boo = foo; } else { boo = 10; } prn(`boo via if-else: ${boo}`);
let foo, boo; foo = 0; prn('Expecting: 0'); //option #1 -- null guard using nullish coalescing operator //quite simply, if foo is null/undefined we default to 10 boo = foo ?? 10; prn(`boo via nullish coalescing operator: ${boo}`); //option #1B -- null guard using logical OR operator //this yields unexpected results (the reason #1 is better) boo = foo || 10; prn(`boo via logical OR: ${boo}`); //option #2 -- null guard using our friend ternary boo = (foo != null) ? foo : 10; prn(`boo via ternary: ${boo}`); //option #3 -- null guard using old fashioned if-else //we use loose comparison "!=" which matches undefined and null if (foo != null) { boo = foo; } else { boo = 10; } prn(`boo via if-else: ${boo}`);