10 4 1 4 boolean functions

Solutions on MaxInterview for 10 4 1 4 boolean functions by the best coders in the world

showing results for - "10 4 1 4 boolean functions"
Victoire
13 Nov 2017
1/*A function that returns a boolean value is known as a boolean function. 
2Perhaps the simplest such function is one that tests an integer to 
3determine if it is even.*/
4
5function isEven(n) {
6   if (n % 2 === 0) {
7      return true;
8   } else {
9      return false;
10   }
11}
12
13console.log(isEven(4));
14console.log(isEven(7));
15
16//true
17//false
18
19
20/*Let's return to the isEven function above, to see how we can use the
21power of return statements to make it even better.
22
23Since return terminates the function, we can leave out the else clause
24and have the same effect. This is because if n is even, the return 
25statement in the if block will execute and the function will end. 
26If n is odd, the if block will be skipped and the second return 
27statement will execute.*/
28
29function isEven(n) {
30   if (n % 2 === 0) {
31      return true;
32   }
33   return false;
34}
35
36console.log(isEven(4));
37
38//true 
39
40This updated version works exactly the same as our initial function.
41
42/*Additionally, notice that the function returns true when n % 2 === 0 
43returns true, and it returns false when n % 2 === 0 returns false. 
44In other words, the return value is exactly the same as the value of 
45n % 2 === 0. This means that we can simplify the function even further
46by returning the value of this expression.*/
47
48function isEven(n) {
49   return n % 2 === 0;
50}
51
52/*This version of isEven is better than the first two, not because it
53is shorter (shorter isn't always better), but because it is simpler 
54to read. We don't have to break down the conditional logic to see 
55what is being returned.
56
57Most boolean functions can be written so that they return the value
58of a boolean expression, rather than explicitly returning true or
59false.*/