CC-02: Conditionals 2
with Carmen Salas • 2024/10/03
Logical Operators
and
and or
are the ones that we use for JavaScript
. Unlike equality operators, logical operators don't necessarily evaluate into boolean
.
Short Circuiting
if (1 > 3 && 13 > 5) {
return true;
} else { return false; }
On operations concerning logical operators, most languages (JavaScript
obviously included), evaluates the operands from left to right. This creates an interesting behavior called short-circuiting. If any of the operands that come first is enough to satisfy either &&
or ||
, the second operand will not be run at all.
Code Challenge
Write a function named
greatestOfThree
that takes in three integer arguments and returns the largest of all arguments. Solve this problem without using any sorting JS methods. You can assume all integers will be different values.
const greatestOfThree = (x,y,z) => {
if (x > y) {
if (x > z) { return x; }
return z;
} else {
if (y > z) { return y; }
return z;
}
}
// tests
console.log(greatestOfThree(-5,-2,-6)); // returns -2
console.log(greatestOfThree(3,2,11)); // returns 11
Write a function named
distinstThree
that takes in three integer arguments and returns a boolean if all the three arguments are distinct. Distinct integers are integers that are not equal to each-other.
const distinstThree = (x,y,z) => {
if (x == y || x == z || y == z) {
return false;
}
return true;
}
// tests
console.log(distinstThree(5,2,6)); // returns true
console.log(distinstThree(3,2,3)); // returns false
Write a function named
isEvenAndPositive
that checks if a number is both even and positive. This function should return a boolean.
const isEvenAndPositive = (num) => {
if ((num % 2 == 0) && num >= 0) {
return true;
}
return false;
}
// tests
console.log(isEvenAndPositive(4)); // returns true
console.log(isEvenAndPositive(-4)); // returns false
Write a function named
leastOfFour
that takes in four integer arguments and returns the least of all arguments. Solve this problem without using any sorting JavaScript methods. You can assume all integers will be different values.
const leastOfFour = (a,b,c,d) => {
let least = a;
if (b < least) { least = b; }
if (c < least) { least = c; }
if (d < least) { least = d; }
return least;
}
// tests
console.log(leastOfFour(-5,-2,-6,0)); // returns -6
console.log(leastOfFour(10,2,6,11)); // returns 2
Last updated