how can you use ! and && instead of ||? - javascript

How can you write an or function without using || operator? ! and && are permissible.
var output = or(true, false);
console.log(output); // --> true;

There are two basic tautologies that you just have to combine. For any a, b:
De Morgan's law: !(a && b) if and only if !a || !b
Double negation: !!a if and only if a
Thus a || b if and only if !(!a && !b) so
function or(a, b) {
return !(!a && !b);
}
That being sad this is only true if a, b are boolean. Note that || operator in JavaScript has side effect:
> var a = 'foo';
> var b = 'bar';
> a || b
'foo'
but
> !(!a && !b)
true
I doubt this can be achieved solely with ! and &&. However this can be implemented without ||:
function or(a, b) {
if (a) {
return a;
}
return b;
}
This still is not 100% the same as ||. That's because a || b evaluates b only if a is false. In particular for functions f() || g() the call g() will be evaluated only when f() is false. So this is another side effect of || which I don't think can be emulated by a function at all.

When is or true?
Whenever either A is true or B is true -- but that answer includes the word "or".
So let's put it another way: whenever it is not the case that both A is false and B is false.

!a && !b = !(a || b)
!a || !b = !(a && b)
!(a || b) = (a || b) else
so to answer your question
!a && !b else // this is the or
but that is a horrible thing to do. Use positive logic and all the tools available to make your code readable.

Are you asking something like this?
var a;
var b = 3;
console.log(a || b);
console.log(!a && b);

Just because I wanted to prove to myself the original question is entirely possible ;) and I didn't use a |
function or(a, b){
var c = console.log;
console.log = function(input) {
c.apply(console, [input]);
window.output = !window.output;
}
return !(!a && !b);
}
// OP Question
var output = or(true, false);
console.log(output); // --> true;
console.log(output); // --> false;

Related

Is there a way to know the value of a variable in an if statement without knowing what the variable is?

I am trying to find out the value of the second variable in the if statement without knowing what the variable is.
EX:
//a, b, and c are controlled by the user in input boxes.
let a = "Josh"
let b = "James"
let c = ""
if (a.length!== 0 && b.length !== 0|| a.length !== 0 && c.length !== 0){
Here I want to check if a equals the value that the length doesn't equal 0. In this case b.
Ex:
if (a == secondVariable){
alert("WOOH")
}
I know I can write
if (a.length !== 0 && b.length !== 0){
if (a == b){
alert("WOOH")
}
} else if (a.length !== 0 && c.length !== 0){
if (a == c){
alert("BOOH")
}
} else {
alert("")
}
But this is a lot of code and I have a lot more variables to check in my code. Is there a more efficient way to write this? Thank you
You can combine the ifs. Also you only need to check the length of one thing if you are also comparing it vs other thing. Also there is a shortcut coercing the length property to a boolean:
if (a.length && a == b) {
alert("WOOH");
}
if (a.length && a == c) {
alert("BOOH");
}

What does the first operand on var __decorator = (this && this.__decorate) || function() {...} try to do?

When TypeScript decorator (class-decorator) gets transpiled to JavaScript it yields this:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Now, what gets assigned to var __decorate variable when the (this && this.__decorate) returns true?
Also, if it gets abandoned how does it affect the whole code?
JS does not nessesarily return true or false from a logical statement. A || B will return A if it is truthy or B if A is falsy. Similarly A && B will return A if it is falsy and B otherwise.
Both || and && are also so-called short-circuit operators where the second operand is not even executed if it is not needed in order to determine the result. So (A && A.B) is often used to get the value of A.B while guarding against A being undefined, or A = B || C used to set A to B if it is defined, or to declare the definition C if it is not.
See, for example, MDN for more details.
(this && this._decorate) looks like it is checking if _decorate is already defined on this. First it is checking if this is defined (otherwise an error would be thrown) then checking the value. If this._decorate is already defined then the function declaration will be skipped (as the existing this._decorate function will be truthy as all functions are).
The only JS operator which is guaranteed to return an actual boolean value is the not operator !.

Conditional logical operator using four variables

I have a function that returns a condition using four variables.
(payload, variables) => {
return payload.newMessage.lenderId === variables.lenderId && payload.newMessage.user.id === variables.authId
}
I want to be able to say C === D is only if C and D exists. What would be the optimal expression for this? So A === B is a sufficient condition if C and D doesn't exist, but if C and D exist, A === B and C === D both have to be met.
A and B must always be equal, and one of the following must be true:
There is no C
There is no D
C and D are equal
(A === B) && (!C || !D || C === D)
Beyond this construction, you should know what you mean by "exists" - is it enough that they not be undefined? Is it any truthy value? Etc.
function customCheck(a,b,c,d) {
const abComparison = a === b;
if (c && d) {
return abComparison && (c === d);
}
return abComparison;
}
From your description seems something like above?

Can this Expression be simplified

I need to simplify this expression
var foo = (!A && B && C) || (A && B && !C) ;
Can anyone suggest a good simplification using minimal operators ?
B is common in both condition, for rest conditional operator can be used.
var foo = B && (A ? !C : C);
Its an XOR operation, do read Logical XOR in JavaScript
Since (!A && C) || (A && !C) is the expansion of XOR, you can replace that part with an XOR expression:
var foo = B && (!!A ^ !!C);

invert a boolean expression

I have some code like this
var a = returnsABoolean();
var b = returnsABoolean();
if (!a || !b) {
} else {
doStuff();
}
How would I invert the test in the if-statement such that I can rewrite this as
var a = returnsABoolean();
var b = returnsABoolean();
if (someExpression) {
doStuff();
}
In other words, what test should I replace someExpression with to preserve the existing behaviour?
You need to apply De Morgan's theorem. Which states:
!A || !B == !(A && B)
Therefore your test can be re-written as:
if (a && b) {
doStuff();
}
Why does it work?
Basically, applying De Morgan's theorem you first rewrite your statement as:
if ( ! (a && b) ) {
} else {
doStuff();
}
Since we now want to invert !(a&&b) we simply remove the not:
if ( (a && b) ) {
doStuff();
}
De Morgan's law states that you can rewrite !a || !b as !(a&&b)
This also works the other way: !a && !b can be rewritten as !(a||b)
Simply assign the logical inverse of your conditional to your previous scope's "else" statement.
if( a && b ) {
doStuff();
}

Categories