CoreJS: Booleans, Truthiness, and Conditionals
15 Jul 2015Boolean operators Part 1: Boolean Logic
Consider the following pieces of code and calculate by hand what value they should calculate, then check your results by entering them into the console.
- true || false
- ((true || false) && false) || true
- var x; (x < 10) || (x > 10);
- !!false
- !((x >= 0) && (x <= 10)) === (!(x >= 0) || !(x <= 10))
- !((x >= 0) && (x <= 10)) === ((x < 0) || (x > 10))
- var x=1, y=1; x === y === 1;
- var x = 0; -1 < x < 1
Boolean Operators Part 2: Non-Boolean values and Truthiness
- 'coffee' || 'tea'
- 'coffee' && 'tea'
- 2 && 1 && 0
- 2*Infinity && 'beyond'
- undefined || false
- undefined || undefined
- 'banana'/2 || 'false'
- var x, y=1; x || y;
- var x = 0; (x === 1 || 2)
Conditionals
Consider the following fragments of code: execute them by hand, as shown in class, and then compare your answers to what you get from running the examples in scratchpad.
1.
var x;
if (x || (x=10)) {
console.log(x);
} else {
if (x && (+"totes a string")){
console.log("one thing");
} else {
console.log("another thing");
}
}
2.
if (x || !x) {
console.log("We've excluded the middle");
} else {
console.log("The middle is not excluded");
}
Boolean Operators Part 3: Short-circuting
Consider the following fragments of code and try to follow the logic of their execution and their outcome:
- true || arglebarg
- if (doJShomework() || runMarathon()) deserveCookie();
- if (doJShomework() && runMarathon()) deserveCookie();
- (backup = '') && deleteAllFiles()
- treat() || trick()
- practice() && win() && celebrate()
Summary
Summarize the following ideas in your own words:
- if-statements
- branching
- booleans
- truthiness
- short-circuiting
After you're done, share your answers within your group and discuss them.