How to simplify this boolean / tenary expression? - javascript

How would I simplify this ternary expression?
c = a === false && b === false ? true : false;
c is true only when a and b are false.

You don't need ternary expression here. The first expression itself returns are Boolean
c = a === false && b === false
Another trick you can use is compare a !== false with b
c = a !== false === b
Here there are only two values to check. If there are more values then its better use every method.
c = [a,b].every(x => x === false)

Related

Comparing 3 identical values for equality using Javascript [duplicate]

This question already has answers here:
Javascript compare 3 values
(7 answers)
Closed 2 years ago.
I am working on studying for an entry test, and being self learned I have been working a lot of functions problems. this one has stumped me,
I a to write a function testing to see if 3 values are equal. The code i have tired is:
Function equal(a,b,c){
return a==b==c;
}
as well as:
function equal(a,b,c){
let newEqual=a==b;
return newEqual===c
}
I feel like I am missing something rather simple but have not been able to put my finger on it.
thank you in advance for any insight
a == b == c will be evaluated as :
a == b then checks the result ( true ) and compares it with c => true == c which is false :
const a = 5;
const b = 5;
const c = 5;
const result = a == b == c ;
console.log(result); // false
const a1 = 5;
const b1 = 5;
const c1 = true;
const result1 = a1 == b1 == c1 ;
console.log(result1); // true
You should compare them separately :
const a = 5;
const b = 5;
const c = 5;
const result = a == b && b == c ;
console.log(result);
To check whether all three variables are equal or not, use && operator to add on queries.
&& returns true if all conditions are true.
function equal(a,b,c){
return a == b && b == c;
}
As mentioned by #mplungjan, for strict comparison use === instead of ==.
Try this.
function equal(a,b,c){
return a==b && b==c;
}
You can check it by doing the following:
function equal(a,b,c){
return (a==b) && (b==c)
}
That way you are checking if a == b is true, and b == c is true then all three are equal. In other words, true && true = true

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?

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

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;

Is that js expression safe: if( !x || doSomething( x[prop], y[prop] ) === false )

From a bug report, I think that the following expression might throw an exception if x is null:
if ( !x || doSomething( x[prop], y[prop] ) === false )
The exception is:
Cannot read property 'prop' of null
... as if the right side of the || is evaluated even if the left side is true.
The javascript reference seems to indicate that that should not happen, but I'm not sure. I've tested that just writing x = null does not (always) crash, but is it guaranteed on every JS engine ?
EDIT:
Same question about
if( x && foo( x[prop] ) === true && bar() === false )
One way to put it is, does :
if( a && b && c )
... evaluates b or c if a === false ? The doc is not clear about that case, only for "a && ( expr1 && expr2 )", not "a && expr1 && expr2"
Full code snippet
var x = null;
var y = {
"p1": "p1",
"p2": "p2"
};
function f() {
return true;
}
for (var propName in y) {
if (x && f(y[propName]) === true && f(y[propName]) === false) {
doSomething(x[propName], y[propName]);
} else if (!x || f(x[propName], y[propName]) === false) {
console.log(y[propName]);
}
}
EDIT2: for completeness, the real (minimized) code that run in the browser
function a(c, b, e, f) {
for (var d in b) {
if (c && _.isObject(b[d]) === true && _.isArray(b[d]) === false) {
a(c[d], b[d], e, d + ".")
} else {
if (!c || _.isEqual(c[d], b[d]) === false) {
e.push({
name: f + d,
value: b[d]
})
}
}
}
return e
}
The Javascript || operator is short-circuiting. The right-hand side will not evaluate if the left-hand side is true. That's a fundamental property of the operator and should be equally implemented across all engines.
Therefore, the right-hand side will only evaluate if x is truthy, and all truthy values in Javascript should be subscriptable without error.
Having said that, y is completely unknown in this example and might throw an error.
"Is it guaranteed on every JS engine?"
We can't actually know that for sure, but the standard defines, how these operators should be implemented.
Logical OR:
Let lref be the result of evaluating LogicalORExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is true, return lval.
Let rref be the result of evaluating LogicalANDExpression.
Return GetValue(rref).
http://es5.github.io/#x11.11
Item 3 doesn't leave any room to doubts, lval is returned immediately if lref can be evaluated to truthy, and rref will never be evaluated.
if (typeof y != 'undefined' && typeof x != 'undefined' && x !== null && y !== null) {
if (doSomething( x[prop], y[prop] ) === false) {
//do stuff
}
}
do the safety check before. this should be working
but note:
if your prop Attribute does not exist, this will return an error too!
greetings

How can I test two strings for equivalence in JavaScript, considering null and empty string the same?

If I compare "a" and "b", that should be false.
If I compare "a" and "a", that should be true.
If I compare "" and null, that should be true.
I could write my own method, but thought there was perhaps a JavaScript shortcut.
Edit: I was thinking something like this:
areDbSame(s1, s2) {
if (s1 === null) s1 = "";
if (s2 === null) s2 = "";
return s1 === s2;
}
Edit2: Settled on this version:
areDbSame(s1, s2) {
return (s1 === null ? "" : s1) === (s2 === null ? "" : s2);
}
Just before you test the equality of your string, you could do a simple one line enforcement, by converting to '' in the case of null. For example (if you also don't care about undefined, false, etc):
// testString becomes the one you are testing
var testString = myString || '';
If you only want to ensure null is blank
var testString = (myString === null) ? '' : myString;
Then you can simply do your string comparisons using testString, and not worry about the null equalities.
IMO this is the cleanest answer because it doesn't convolute the original equality testing of javascript strings. It is the same as saying, let's split the problem up into two parts.
1) When should my string be considered blank, and
2) Now I can just check for regular string equality.
function areEqualStrings(a, b) {
var otherEqualValues = ['', null];
if(typeof a === 'string' && typeof b === 'string') {
return a === b;
} else if(otherEqualValues.indexOf(a) > -1 && otherEqualValues.indexOf(b) > -1) {
return !a === !b;
} else {
return false;
}
}
When coercing JavaScript values, !null is true and !'' is true, so those would result in being equal.
Here's the test (screenshotted from my console):
This function should do it. It type checks first and short circuits otherwise.
function stringCompare(a, b) {
if (((a === null || typeof a === 'string') ||
(b === null || typeof b === 'string')) &&
((a === '' && b === null) ||
(b === '' && a === null) ||
(a === b))) {
return true;
}
return false;
}
No it hasn`t. The two first cases you can do naturally using operator =.
The third case it is impossible because "" is considered a empty string and null has any type. So they never can be true naturally. To do this, you have to write your own method.
Just to be clear. You can use operators = (equal) to do comparison:
== equal to
`x == 8 false
x == 5 true
x == "5" true
=== equal value and equal type
x === 5 true
x === "5" false
Hope it helps

Categories