Write a Function 'or' without '||' - javascript

Write a function 'or' without ||
Given 2 boolean expressions, "or" returns true or false, corresponding to the || operator.
*Should use ! and &&
function or(expression1, expression2) {
return !expression1 && expression1 && !expression2 && expression1
}
I've tried that but at the same time I'm confused on what the question is exactly asking
Expected Output:
var output = or(true, false);
console.log(output); // --> true;

Some basic consideration, with De Morgan's laws:
!(a && b) = !a || !b
!(a || b) = !a && !b
function or(a, b) {
return !(!a && !b);
}
console.log(or(false, false)); // false
console.log(or(false, true)); // true
console.log(or(true, false)); // true
console.log(or(true, true)); // true

here is the working solution
function or(a, b){
if(!a && !b)
return false
return true;
}
console.log(or(true, true));
console.log(or(true, false));
console.log(or(false, true));
console.log(or(false, false));
hope this helps!!

The concept they are asking you to show is something called a NAND or Not AND
NAND is the most common type of of logic operator in electronics and can be used to represent all other logic.
You can find a representation of what you should be modeling here: https://en.wikipedia.org/wiki/NAND_logic#OR

Your implementation:
return !a && b && !a && b
For true and false this evaluates to:
return !true && true && !false && false;
i.e.
return false && true && true && false;
Because of lazy evaluation, it doesn't even evaluate anything after the first false && because false && x is false regardless of the value of x. For any input, one of the terms is false, so it will always return false.
It may help if you break it into smaller parts:
boolean bothFalse = !a && !b
boolean notBothFalse = !bothFalse;
return notBothFalse;
But using brackets () you can express this in a single line. I'll leave this as an exercise for you.

Related

If !0 is truthy then how come "true && !0" returns true and not !0?

From what I understand if both values are truthy it should return the last truthy value which in this case should be !0.
I'm a not javascript developer, but this is quite simple.
int 0 equals int 0
int 1 equals int 1
int 0 == bool false equals true (it means JS threats 0 as false and casts 0 to bool)
int 1 == bool true equals true (it means JS threats 1 as true and casts 1 to bool)
bool !0 equals true (!0 becomes true, because the opposite of true is false, and 0 is threated here as 0 because ! interprets and casts it as a boolean)
!1 equals false
As far as my javascript knowledge goes, once you use ! it will become a boolean as it tries to cast int to bool.
true && !0 == true because !0 is true.
Basically it's parsing as
true && true == true thus returning boolean true, and not !0.
While the answer of Droppy is correct, it lacks a proper in-depth explanation of the encountered behavior:
!{statement} is in human readable form simply not {statement}.
! is the logical NOT operator, it reverses the truthiness or falsiness of {statement}.
0 in this case is not converted to anything - it is just a falsy value and since ! is an operator, it returns the result of the inverted falsy/truthy match. From the docs:
Returns false if its single operand can be converted to true; otherwise, returns true.
You can easily get the boolean result of a statements falsiness/truthiness by doing: !!{statement}. For your example, !!0 gives false, likewise !!1 gives true.
If we were to write our own logical IS and NOT function according to JS standards, it would look like:
function logicalIs(statement) {
if(statement === undefined) return false;
if(statement === null) return false;
if(statement === false) return false;
if(statement === "") return false;
if(statement === '') return false;
if(statement === 0) return false;
if(typeof(statement) === 'number' && isNaN(statement)) return false;
// document.all: Willful violation for IE legacy reasons
if(statement === document.all) return false;
return true;
}
function logicalIsNot(statement) {
if(statement === undefined) return true;
if(statement === null) return true;
if(statement === false) return true;
if(statement === "") return true;
if(statement === '') return true;
if(statement === 0) return true;
if(typeof(statement) === 'number' && isNaN(statement)) return true;
// document.all: Willful violation for IE legacy reasons
if(statement === document.all) return true;
return false;
}
let truthy = [true, 1, 'a', "b", [], {}, function(){}];
let falsy = [false, 0, '', "", NaN, null, undefined, document.all];
console.log('logical truthy: ', JSON.stringify(truthy.map(logicalIs)));
console.log('logical falsy: ', JSON.stringify(falsy.map(logicalIs)));
console.log('logical not truthy:', JSON.stringify(truthy.map(logicalIsNot)));
console.log('logical not falsy:', JSON.stringify(falsy.map(logicalIsNot)));

Performing xnor in javascript

I have two strings stored in a & b. I want to perfrom some validation if both strings have some value. For this I use:
if(a && b) {
//Do some processing.
}
However if one of them is empty and the other is not, then I need to treat it separately. If both are empty, I don't need to do anything. So basically to handle this case it is the false case of XNOR.
I could do this way:
if((a && !b) || (!a && b)) {
//handle separately.
}
Is there a better approach than this?
Let's combine your two separate if-statements into one (effectively the same, but will help with the simplification):
if (a && b)
// do some processing
else if (a && !b || !a && b)
// do other processing
To figure out if we can simplify further, let's look at the truth table for the second condition:
a | b | x
--------------
1 | 0 | 1 (a && !b)
0 | 1 | 1 (!a && b)
0 | 0 | 0 (a && b) (negating the first if)
You can see that the positive outcomes (x = 1) are present when a is true or when b is true, which simplifies to a || b. The final version of your if-statement would look like:
if (a && b)
// do some processing
else if (a || b)
// do other processing
JavaScript does not have XOR and XNOR operators. There are many ways to implement them, and the way you implemented it is fine. Another way can be by using the ternary operator:
//XOR
if( a ? !b : b ) {
...
}
//XNOR
if( a ? b : !b ) {
...
}
However, all those methods have a downside of potentially evaluating a and b more than once. That can be a problem if a or b is a function or expression. A better approach can be by rewording the definition of XOR to: return true if the two boolean operands do not have the same value. We can implement that like this:
//XOR
if( a != b ) {
...
}
//XNOR
if( a == b ) {
...
}
Now, this is much shorter and, more importantly, only evaluates a and b once. However, this only works if both a and b are booleans. If you want to support other types, you'll have to convert them to booleans first:
//XOR
if( !a != !b ) {
...
}
//XNOR
if( !a == !b ) {
...
}

Why '=' and '||' will be evaluated to be true?

I read this post, it mentioned this if (variable == 1 || 2 || 6) cannot work (JS Short for if (a == b || a == c)).
But I tried this example, it will be evalauted to be true, why?
var a = 'apple';
if('apple2' == a || 'banana' ) {
alert('hi');
}
Here is the working example:
https://jsfiddle.net/Loun1ggj/
Update:
if('apple2' == a || 'banana' ) is not evaluated into if('apple2 == a' || 'apple' == 'banana')?
Let's break down the expression:
if('apple2' == a || 'banana' )
The first part to be evaluated is the ==, because it has highest operator precedence:
'apple2' == a
This is a standard equality, and returns false, giving us:
if(false || 'banana')
The || operator in JS returns not true or false, but whichever of its arguments is "truthy". A non-empty string like 'banana' is considered "truthy", so we end up with this:
if('banana')
Now we again look at the "truthiness" of 'banana', and the if statement proceeds.
Since 'banana' is always true, it would always run, see the below example
var a = 'apple';
if('apple2' == a) {
alert('hi');
}
if('banana'){
alert('hello');
}
if('apple2' == a || 'banana' ) is evaluated this way:
if(('apple2' == a) || ('banana') ), which is:
if :
'apple2' == a // false
||(or)
'banana' // true, since Boolean('banana') is true (a non-empty string is a truthy value)
so => if (false or 'banana') => if ('banana') // => true
It's not evaluated as if('apple2' == a || 'apple2' == 'banana' ).
According to this, the operator == has higher precedence over operator ||. So the expression is evaluated as follows:
if('apple2' == a || 'banana' )
'apple2' == a //false
'banana' //true (non-empty string)
So final evaluation will be, always true:
if(false || true) //true
There's 2 expressions here
'apple2' == a which resolve to falsy
'banana' which resolve to thruthy
Because 'banana' is not undefined or null essentially.

How can I break the law of non-contradiction in Javascript?

The law of non-contradiction dictates that two contradictory statements cannot both be true at the same time. That means that the expressions
(a && !a)
(a == !a)
(a === !a)
should always evaluate to a falsy value, and
(a || !a)
should always evaluate to a truthy value.
Fortunately, though, Javascript is a fun language that allows you to do all sorts of sick things. I bet someone a small fortune that it's possible to convince Javascript to break the law of non-contradiction, or, at least, convincingly make it look like it's breaking the law of non-contradiction. Now I'm trying to make all four of the above code examples give the unexpected result.
What would be a good way to go about this?
The best I can do is:
[] == ![] // true
or
var a = [];
a == !a
Of course this is really doing [] == false // true and !![] == ![] // false. It's really just a technicality.
EDIT: This is really a joke, but does work:
var a = false; var b = function() { return a = !a };
console.log(!!(b() && !b())); // true
console.log(b() == !b()); // true
console.log(b() === !b()); // true
console.log(b() || !b()); // true
This one will do the trick:
var a = '0';
a == !a
(evaluates to true)
In this case, a == false and !a == false.
a=NaN;
var a=NaN,
A=[(a && !a), (a == !a),(a === !a),(a || !a)];
alert(A)
/* returned value: (Array)
NaN,false,false,true
*/
I still haven't found anything to break && and ===, but here's one for == and ||:
Object.prototype.toString = function() {
return false;
};
a = {};
b = (a || !a);
alert(a || !a); //alerts false
alert(b == !b); //alerts true

Javascript Logical Operator:?

I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
It is just an obtuse way to cast the result to a boolean.
Yes, it's NOT-NOT. It is commonly used idiom to convert a value to a boolean of equivalent truthiness.
JavaScript understands 0.0, '', null, undefined and false as falsy, and any other value (including, obviously, true) as truthy. This idiom converts all the former ones into boolean false, and all the latter ones into boolean true.
In this particular case,
a && b
will return b if both a and b are truthy;
!!(a && b)
will return true if both a and b are truthy.
The && operator returns either false or the last value in the expression:
("a" && "b") == "b"
The || operator returns the first value that evaluates to true
("a" || "b") == "a"
The ! operator returns a boolean
!"a" == false
So if you want to convert a variable to a boolean you can use !!
var myVar = "a"
!!myVar == true
myVar = undefined
!!myVar == false
etc.
It is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
It will convert anything to true or false...

Categories

Resources