Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simplify `(variableA && !variableB) || !variableA` expression in JavaScript?

Tags:

javascript

Please see this minimum example:

const result = (variableA && !variableB) || !variableA;

In this expression, I can't simply write this

const result = variableA && !variableB;

Because if variableA = 0, the result will be different

const variableA = 0;
const variableB = undefined;

console.log((variableA && !variableB) || !variableA); // true
console.log(variableA && !variableB); // 0

Is there any way I can simplify this expression?

like image 723
Joseph Wang Avatar asked Apr 30 '20 11:04

Joseph Wang


People also ask

What is the easiest way to simplify variable expressions?

Simplifying variable expressions requires you to find the values of your variables or to use specialized techniques to simplify the expression (see below). Our final answer is "2x + 32".

How do I use the simplify calculator?

Simplify Calculator. Step 1: Enter the expression you want to simplify into the editor. The simplification calculator allows you to take a simple or complex expression and simplify and reduce the expression to it's simplest form. The calculator works for both numbers and expressions containing variables. Step 2:

How do you simplify complex expressions in math?

Simplifying Complex Expressions Add like variable terms. When dealing with variable expressions, it's important to remember that terms with the same variable and exponent (or "like terms") can be added and subtracted like normal numbers. Simplify numerical fractions by dividing or "canceling out" factors.

What does it mean to simplify algebraic expressions?

Simplifying an algebraic expression means writing the expression in the most basic way possible by eliminating parentheses and combining like terms. For example, to simplify 3x + 6x + 9x, add the like terms: 3x + 6x + 9x = 18x.


2 Answers

You could use

!(a && b)

or the equivalent with De Morgan's laws

!a || !b

const
    f = (a, b) => (a && !b) || !a,
    g = (a, b) => !(a && b),
    h = (a, b) => !a || !b

console.log(0, 0, f(0, 0), g(0, 0), h(0, 0));
console.log(0, 1, f(0, 1), g(0, 1), h(0, 1));
console.log(1, 0, f(1, 0), g(1, 0), h(1, 0));
console.log(1, 1, f(1, 1), g(1, 1), h(1, 1));
like image 111
Nina Scholz Avatar answered Oct 23 '22 18:10

Nina Scholz


(variableA && !variableB) || !variableA; if we use factoring to this result below

(!variableA  || variableA) && (!variableA ||!variableB)

first part is always true then only second part is enough for u

!variableA ||!variableB

const variableA = 0;
const variableB = undefined;
console.log((variableA && !variableB) || !variableA); // true
console.log(!variableA ||!variableB);
like image 25
mr. pc_coder Avatar answered Oct 23 '22 19:10

mr. pc_coder