Thursday, May 6, 2021

Javascript Practice 38: JS Hero - Boolean

 
Question: 

Write a function nand that takes two Boolean values. If both values are true, the result should be false. In the other cases the return should be true.

I.e.: The call nand(true, true) should return false. The calls nand(true, false), nand(false, true) and nand(false, false) should return true.




Answer: 

function nand (boo1, boo2) {

if (boo1 === true && boo2 === true) {
return false;} else {return true}

}; 


or 


function nand (b1, b2) {

let and = b1 && b2; 

return !and

};


> what is a Boolean
> a Boolean is a value that either represents true or false
> the reason we use Booleans, is to evaluate certain circumstances 
> it is not a string but a Boolean (keyword)
> in the question we have to write a function 'nand' that takes two Boolean values as parameters
> we then evaluate them 
> if both values are true then our result should be false
> the first solution is fairly simple with the use of if and else statements
>>> we clearly mention that if both the values are true then the function should return false
>>> else it should return true for all other scenarios
> the second solution is a bit complicated but this will help you understand the usage of Booleans much better
>>> JS has three Boolean operators: &&, || and !
>>> && = and    
>>> || = or
>>> ! = not 
>>> && links two Boolean values; if both values are true, then result is true or else in all other cases it is false
>>> || is true if at least one of the two input values is true; if both values are false then the result is false
>>>  ! is applied to a single Boolean value and inverts this value; !true (not true) = false and !false (not false) = true
>>> in our second solution we first declare a variable 'and'
>>> we initialize it with a value of both our Boolean parameters
>>> like this b1 && b2
>>> so if b1 and b2 are true, then variable 'and' will store the value true and in all other cases it will store the value of false
>>> so if we return the variable 'and' then we shall get the value 'true'
>>> but we need the returned value to be 'false' if both the values are true 
>>> so instead of 'and' if we return '!and' (not and) then we shall get the value false 
> finally we have created a function called nand but in coding it is called a NAND gate 

No comments:

Post a Comment