javascript why is (true)^2 = 3, (true)^3=2 [duplicate] - javascript

What are XAND and XOR? Also is there an XNot

XOR is short for exclusive or. It is a logical, binary operator that requires that one of the two operands be true but not both.
So these statements are true:
TRUE XOR FALSE
FALSE XOR TRUE
And these statements are false:
FALSE XOR FALSE
TRUE XOR TRUE
There really isn't such a thing as an"exclusive and" (or XAND) since in theory it would have the same exact requirements as XOR. There also isn't an XNOT since NOT is a unary operator that negates its single operand (basically it just flips a boolean value to its opposite) and as such it cannot support any notion of exclusivity.

Guys, don´t scare the crap out of others (hey! just kidding), but it´s really all a question of equivalences and synonyms:
firstly:
"XAND" doesn´t exist logically, neither does "XNAND", however "XAND" is normally thought-up by a studious but confused initiating logic student.(wow!). It com from the thought that, if there´s a XOR(exclusive OR) it´s logical to exist a "XAND"("exclusive" AND). The rational suggestion would be an "IAND"("inclusive" AND), which isn´t used or recognised as well. So:
XNOR <=> !XOR <=> EQV
And all this just discribes a unique operator, called the equivalency operator(<=>, EQV) so:
A | B | A <=> B | A XAND B | A XNOR B | A !XOR B | ((NOT(A) AND B)AND(A AND NOT(B)))
---------------------------------------------------------------------------------------
T | T | T | T | T | T | T
T | F | F | F | F | F | F
F | T | F | F | F | F | F
F | F | T | T | T | T | T
And just a closing comment: The 'X' prefix is only possible if and only if the base operator isn´t unary. So, XNOR <=> NOT XOR <=/=> X NOR.
Peace.

XOR is Exclusive Or. It means "One of the two items being XOR'd is true, but not both of them."
TRUE XOR TRUE : FALSE
TRUE XOR FALSE : TRUE
FALSE XOR TRUE : TRUE
FALSE XOR FALSE: FALSE
Wikipedia's XOR Article
XAND I have not heard of.

In the book written by Charles Petzold titled "Code" he says there are 6 gates. There is the AND logical gate, the OR gate, the NOR gate, the NAND gate, and the XOR gate. He also mentions the 6th gate briefly calling it the "coincidence gate" and implies it's not used very often. He says it has the opposite output of a XOR gate because a XOR gate has the output of "false" when it has two true or two false sides of the equation and the only way for a XOR gate to have its output be true is for one of the sides of the equation to be true and the other to be false, it doesn't matter which. The coincidence is the exact opposite of this because with the coincidence gate if one is true and the other is false (doesn't matter which is which) then it will have its output be "false" in both those cases. And the way for a coincidence gate to have its output be "true" is for both sides to be either false or true. If both are false the coincidence gate will evaluate as true. If both are true then the coincidence gate will also output "true" in that case as well.
So in the cases where the XOR gate outputs "false", the coincidence gate will output "true". And in the cases where the XOR gate will output "true", the coincidence gate will output "false".

Hmm.. well I know about XOR (exclusive or) and NAND and NOR. These are logic gates and have their software analogs.
Essentially they behave like so:
XOR is true only when one of the two arguments is true, but not both.
F XOR F = F
F XOR T = T
T XOR F = T
T XOR T = F
NAND is true as long as both arguments are not true.
F NAND F = T
F NAND T = T
T NAND F = T
T NAND T = F
NOR is true only when neither argument is true.
F NOR F = T
F NOR T = F
T NOR F = F
T NOR T = F

There is no such thing as Xand or Xnot. There is Nand, which is the opposite of and
TRUE and TRUE : TRUE
TRUE and FALSE : FALSE
FALSE and TRUE : FALSE
FALSE and FALSE : FALSE
TRUE nand TRUE : FALSE
TRUE nand FALSE : TRUE
FALSE nand TRUE : TRUE
FALSE nand FALSE : TRUE

To add to this, since I was just dealing with it, if you are looking for an "equivalence gate" or a "coincedence gate" as your XAND, what you really have is just "equals".
If you think about it, given XOR from above:
F XOR F = F
F XOR T = T
T XOR F = T
T XOR T = F
And we expect XAND should be:
F XAND F = T
F XAND T = F
T XAND F = F
T XAND T = T
And isn't this exactly the same?
F == F = T
F == T = F
T == F = F
T == T = T

There's a simple argument to see where the binary logic gates come from, using truth tables, which have come up already.
There are six that represent commutative operations, in which a op b == b op a. Each binary operator has an associated three column truth table that defines it. The first two columns can be fixed for the defining tables for all the operators.
Consider the third column. It's a sequence of four binary digits. There are sixteen combinations, but the constraint of commutativity effectively removes one row from the truth tables, so it's only eight. Two more get knocked off because all truths or all falses isn't a useful gate. These are the familiar or, and, and xor, plus their negations.

This is what you are looking for:
https://en.wikipedia.org/wiki/XNOR_gate
Here is the logic table:
A B XOR XNOR
0 0 0 1
0 1 1 0
1 0 1 0
1 1 0 1
XNOR sometimes is called XAND.

In most cases you won't find an Xand, Xor, nor, nand Logical operator in programming, but fear not in most cases you can simulate it with the other operators.
Since you didn't state any particular language. I won't do any specific language either. For my examples we'll use the following variables.
A = 3
B = 5
C = 7
and for code I'll put it in the code tag to make it easier to see what I did, I'll also follow the logic through the process to show what the end result will be.
NAND
Also known as Not And, can easily be simulated by using a Not operator, (normally indicated as ! )
You can do the following
if(!((A>B) && (B<C)))
if (!(F&&T))
if(!(F))
If(T)
In our example above it will be true, since both sides were not true. Thus giving us the desired result
NOR
Also known as Not OR, just like NAND we can simulate it with the not operator.
if(!((A>B) || (B<C)))
if (!(F||T))
if(!(T))
if(F)
Again this will give us the desired outcomes
XOR
Xor or Exlcusive OR only will be true when one is TRUE but the Other is FALSE
If (!(A > C && B > A) && (A > C || B > A) )
If (!(F && T) && (F || T) )
If (!(F) && (T) )
If (T && T )
If (T)
So that is an example of it working for just 1 or the other being true, I'll show if both are true it will be false.
If ( !(A < C && B > A) && (A < C || B > A) )
If ( !(T && T) && (T ||T) )
If ( !(T) && (T) )
If ( F && T )
If (F)
And both false
If (!(A > C && B < A) && (A > C || B < A) )
If (!(F && F) && (F || F) )
If (!(F) && (F) )
If (T && F )
If (F)
And the picture to help
XAND
And finally our Exclusive And, this will only return true if both are sides are false, or if both are true. Of course You could just call this a Not XOR (NXOR)
Both True
If ( (A < C && B > A) || !(A < C || B > A) )
If ((T&&T) || !(T||T))
IF (T || !T)
If (T || F)
IF (T)
Both False
If ( (A > C && B < A) || !(A > C || B < A) )
If ( (F && F) || !(F ||F))
If ( F || !F)
If ( F || T)
If (T)
And lastly 1 true and the other one false.
If ((A > C && B > A) || !(A > C || B > A) )
If ((F && T) || ! (F || T) )
If (F||!(T))
If (F||F)
If (F)
Or if you want to go the NXOR route...
If (!(!(A > C && B > A) && (A > C || B > A)))
If (!(!(F && T) && (F || T)) )
If (!(!(F) && (T)) )
If (!(T && T) )
If (!(T))
If (F)
Of course everyone else's solutions probably state this as well, I am putting my own answer in here because the top answer didn't seem to understand that not all languages support XOR or XAND for example C uses ^ for XOR and XAND isn't even supported.
So I provided some examples of how to simulate it with the basic operators in the event your language doesn't support XOR or XAND as their own operators like Php if ($a XOR $B).
As for Xnot what is that? Exclusive not? so not not? I don't know how that would look in a logic gate, I think it doesn't exist. Since Not just inverts the output from a 1 to a 0 and 0 to a 1.
Anyway hope that helps.

The truth tables on Wiki clarify http://en.wikipedia.org/wiki/Logic_gate
There is no XAND, and that is the end of part 1 of the questions legitimacy.
[The point is you can always make do without it.]
I personally have mistaken XNOT (which also doesn't exist) for NAND and NOR which are theoretically the only thing you need to make all the other gates link
I believe the confusion stems from the fact that you can use either NAND or NOR (to create everything else [but they are not needed together]), so it's thought of as one thing that's both NAND and NOR together, which basically leaves the mind to supplant the remaining name XNOT which isn't used so it's what I wrongly call XNOT meaning it's either NAND or NOR.
I suppose one could also wrongly in quick discussion try to use the XAND like I do XNOT, to refer to the "a single gate (copied in various arrangements) makes all other gates" logical reality.

XOR (not neither and not both) B'0110' is the inverse
(dual) of IFF (if and only if) B'1001'.

XOR behaves like Austin explained, as an exclusive OR, either A or B but not both and neither yields false.
There are 16 possible logical operators for two inputs since the truth table consists of 4 combinations there are 16 possible ways to arrange two boolean parameters and the corresponding output.
They all have names according to this wikipedia article

The XOR definition is well known to be the odd-parity function.
For two inputs:
A XOR B = (A AND NOT B) OR (B AND NOT A)
The complement of XOR is XNOR
A XNOR B = (A AND B) OR (NOT A AND NOT B)
Henceforth, the normal two-input XAND defined as
A XAND B = A AND NOT B
The complement is XNAND:
A XNAND B = B OR NOT A
A nice result from this XAND definition is that any dual-input binary function can be expressed concisely using no more than one logical function or gate.
+---+---+---+---+
If A is: | 1 | 0 | 1 | 0 |
and B is: | 1 | 1 | 0 | 0 |
+---+---+---+---+
Then: yields:
+-----------+---+---+---+---+
| FALSE | 0 | 0 | 0 | 0 |
| A NOR B | 0 | 0 | 0 | 1 |
| A XAND B | 0 | 0 | 1 | 0 |
| NOT B | 0 | 0 | 1 | 1 |
| B XAND A | 0 | 1 | 0 | 0 |
| NOT A | 0 | 1 | 0 | 1 |
| A XOR B | 0 | 1 | 1 | 0 |
| A NAND B | 0 | 1 | 1 | 1 |
| A AND B | 1 | 0 | 0 | 0 |
| A XNOR B | 1 | 0 | 0 | 1 |
| A | 1 | 0 | 1 | 0 |
| B XNAND A | 1 | 0 | 1 | 1 |
| B | 1 | 1 | 0 | 0 |
| A XNAND B | 1 | 1 | 0 | 1 |
| A OR B | 1 | 1 | 1 | 0 |
| TRUE | 1 | 1 | 1 | 1 |
+-----------+---+---+---+---+
Note that XAND and XNAND lack reflexivity.
This XNAND definition is extensible if we add numbered kinds of exclusive-ANDs to correspond to their corresponding minterms. Then XAND must have ceil(lg(n)) or more inputs, with the unused msbs all zeroes. The normal kind of XAND is written without a number unless used in the context of other kinds.
The various kinds of XAND or XNAND gates are useful for decoding.
XOR is also extensible to any number of bits. The result is one if the number of ones is odd, and zero if even. If you complement any input or output bit of an XOR, the function becomes XNOR, and vice versa.
I have seen no definition for XNOT, I will propose a definition:
Let it to relate to high-impedance (Z, no signal, or perhaps null valued Boolean type Object).
0xnot 0 = Z
0xnot 1 = Z
1xnot 0 = 1
1xnot 1 = 0

Have a look
x y A B C D E F G H I J K L M N
· · T · T · T · T · T · T · T ·
· T · T T · · T T · · T T · · T
T · · · · T T T T · · · · T T T
T T · · · · · · · T T T T T T T
A) !(x OR y)
B) !(x) AND y
C) !(x)
D) x AND !(y)
E) !(y)
F) x XOR y
G) !(x AND y)
H) x AND y
I) !(x XOR y)
J) y
K) !(x) OR y
L) x
M) x OR !(y)
N) x OR y

OMG, a XAND gate does exist. My dad is taking a technological class for a job and there IS an XAND gate. People are saying that both OR and AND are complete opposites, so they expand that to the exclusive-gate logic:
XOR: One or another, but not both.
Xand: One and another, but not both.
This is incorrect. If you're going to change from XOR to XAND, you have to flip every instance of 'AND' and 'OR':
XOR: One or another, but not both.
XAND: One and another, but not one.
So, XAND is true when and only when both inputs are equal, either if the inputs are 0/0 or 1/1

First comes the logic, then the name, possibly patterned on previous naming.
Thus 0+0=0; 0+1=1; 1+0=1; 1+1=1 - for some reason this is called OR.
Then 0-0=0; 0-1=1; 1-0=1; 1-1=0 - it looks like OR except ... let's call it XOR.
Also 0*0=0; 0*1=0; 1*0=0; 1*1=1 - for some reason this is called AND.
Then 0~0=0; 0~1=0; 1~0=0; 1~1=0 - it looks like AND except ... let's call it XAND.

Related

How does bitwise operation work on Booleans?

I came across this challenge on Edabit and couldn't work out this bitwise operation solution.
notNotNot = (a,b) => !!(a%2 >> b)
The challenge:
//Something which is not true is false, but something which is not not true is true!
//Create a function where given n number of "not", evaluate whether it's true or false.
//Examples:
notNotNot(1, true) ➞ false
// Not true
notNotNot(2, false) ➞ false
// Not not false
notNotNot(6, true) ➞ true
// Not not not not not not true
I did some research that that operator:
Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
That I reckon I understood (e.g. 5 >> 1 same as 0101 >> 1 which evaluates to 0010), but I can't see how that works with a boolean? I know true evaluates to 1 and false to 0.
The function you gave does not satisfy the challenge. Right shifting will not do what is asked for. For example, your notNotNot(6,true) is false, not true when put through your function.
Your question is about bitwise operation on a boolean though. Since operators like >> and << work on integers, Javascript first converts the boolean value to an integer. So true becomes 1 and false becomes 0. To see this you can shift by zero:
console.log("true is",true >> 0)
console.log("false is", false >> 0)
So bitwise operation on booleans is really just bitwise operation on either 0 or 1.
Using !! is a handy way to convert anything into a boolean. It takes anything that would be considered equivalent to false (such as 0, null, undefined or "") and gives back false. Similarly anything that is truthy (like 14, "hello", [4], {a:1}) and give back true. !! works because the first exclamation mark gives the 'not' of the expression which is always true or false, then the second exclamation mark gives the opposite of that (false or true).
Getting back to the challenge, it wants to apply the not-operator 'a' times and compare to the 'b' value. So something like this would work:
function notNotNot(a, b) { return !!(a%2 - b); }
console.log("notNotNot(1, true)",notNotNot(1, true));
console.log("notNotNot(2, false)",notNotNot(2, false));
console.log("notNotNot(6, true)",notNotNot(6, true));
Bitwise operators always convert their operands to an integer. So, 4 >> true is the same as 4 >> 1 which will do a bit shift right by one position
(decimal) 4 = (binary) 100
(binary) 100 >> 1 = (binary) 010
(binary) 010 = (decimal) 2
console.log(4 >> true);
So, using true or false is a just a roundabout way to use 1 or 0.
The notNotNot function has very simple operation, overall:
a%2 converts the first number into 0 for even or 1 for odd.
>> b shifts right by either 0 positions for false or 1 position for true.
a is odd (1) and b is false = 1
there is zero shifts to the right, so the number remains the same.
a is odd (1) and b is true = 0
the only set bit 1 is shifted right and discarded.
a is even (0) and b is false = 0
there is zero shifts to the right, so the number remains the same.
a is even (0) and b is true = 0
the base number is 0 which doesn't have any bits set, so shifting right any amount does not change it.
!!() converts the result to boolean.
With that said, the solution here is wrong, since notNotNot(2, true) will produce false - a is even and b is true. The expectation is that it will produce true since !!true = true. The same problem is present for any even number and true.
It can be easily fixed by using bitwise XOR instead of right shift:
a is odd (1) and b is false = 1
both match, so they are flipped to 0
a is odd (1) and b is true = 0
they don't match, so we get 1
a is even (0) and b is false = 0
both match, so we get 0
a is even (0) and b is true = 1
they don't match, so we get 1
notNotNot = (a,b) => !!(a%2 ^ b);
console.log("!!true = ", notNotNot(2, true))
console.log("!!!true =", notNotNot(3, true))
console.log("!!false = ", notNotNot(2, false))
console.log("!!!false = ", notNotNot(3, false))
//bonus
console.log("true = ", notNotNot(0, true))
console.log("false = ", notNotNot(0, false))
Just for completeness sake, in case you want a fully bitwise operation:
The modulo operation %2 can be changed to a bitwise AND &1 get the lowest bit. For even numbers, this would yield 0 since you'd be computing
xxx0
&
0001
which is zero. And for odd numbers the same applies but you'd get one as a result:
xxx1
&
0001
So the results of a&1 and a%2 are identical. Furthermore, even though bitwise operations convert the number to a 32-bit signed integer that doesn't matter as the parity would be preserved.
//larger than 31 bits
const largeValue = 2**31 + 1;
//larger than 32 bits
const veryLargeValue = 2**32 + 1
console.log("2**31 + 1 =", largeValue);
console.log("2**32 + 1 =", veryLargeValue);
console.log("2**31 + 1 to 32-bit signed integer =", largeValue | 0);
console.log("2**32 + 1 to 32-bit signed integer = ", veryLargeValue | 0);
const isOddModulo = number =>
console.log(`(${number} % 2) can detect an odd number: ${(number % 2) === 1}`);
const isOddBitwise = number =>
console.log(`(${number} & 1) can detect an odd number: ${(number & 1) === 1}`);
isOddModulo(largeValue);
isOddBitwise(largeValue);
isOddModulo(veryLargeValue);
isOddBitwise(veryLargeValue);
Firstly, (a,b) => !!(a%2 >> b) does not match the results of the examples. I will break down exactly what it's doing using notNotNot(6, true) ➞ true.
Fist a%2, simply get a divide by 2 return the remainder. So we will get 0 for an even number and 1 for an odd number. a = 6 a%2 = 0 in this case.
Then 0 >> b shift 1 number off from the right because as you said true evaluates to 1. So we get 0 >> 1 = 0.
Last !!(0), is simple, and can be broken down like so, !0 = true, then !true = false.
So if we think about this as long as b is true, we will always get returned false. Let's say we have a = 5, b = true evaluating to 5%2 = 1, 1 >> 1 = 0. You can see because of the mod (%2) we will only ever have 1 or 0 (only ever have 1 digit) and true will always shift off the 1 when we have it.
A simple way to look at this problem is like an isEvenOrNot function. So a is the number we are checking and b is a boolean to check if it's even (true) or not even (false). This works because every second not added will be true.
So a solution using bitwise could be something like: (a,b) => !!(a&1 ^ b).
I will let you have the fun of breaking down why it works! :)
A little bit more into explaining how shift works with a boolean. So true as you said will be 1 and false will be 0. So as shown in your example, 0101 >> true is the same as 0101 >> 1.
I hope this helps.
I used the following as a reference for bitwise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
(a%2) //ignore all but the least significant bit (LSB)
(a%2 >> b ) //if TRUE, shifts right, resolves to 0
//if FALSE, no shift, resolves to LSB
// 0 and LSB are both integers so convert to boolean by using logical/boolean NOT
!(a%2 >> b ) //resolves to the boolean which it is NOT
!!(a%2 >> b ) //resolves to the boolean which it is NOT NOT
NB For either boolean,
an even number of NOTs results in the original boolean
an odd number of NOTs results in the opposite boolean
The LSB of any number dictates whether the number is odd or even.(0 even, 1 odd)
I see that your task is:
/* Create a function where given n number of "not",
evaluate whether it's true or false.*/
I don't know why you are writing notnotnot function
for me that is not what the task asks.
So according to the task I made that function not
that accepts a number of "nots" and evaluates them.
The first way
function not(n) {
return Boolean(n - n - 1);
}
The second way using XOr(^)
function not(n) {
return Boolean(bool ^ (bool - 1));
}
The third way using Mod(%) pointed by #VLAZ
function not(n) {
return Boolean(n % 2);
}
The fourth way using bitwise And(&)
function not(n) {
return Boolean(n & 1);
}
Test
not(0)
//> false
not(1)
//> true
not(2)
//> false
not(515)
//> true
Lets analysis solution first
notNotNot(oddNumber, true) ➞ false
notNotNot(evenNumber, true) ➞ true
notNotNot(oddNumber, false) ➞ true
notNotNot(evenNumber, false) ➞ false
Now analysis the for (a,b) => !!(a%2 >> b)
a%2 == 0 ➞ even number
a%2 == 1 ➞ odd number
// For a%2 == 0
a%2 >> b ➞ if b is true ➞ 0 >> 1 ➞ 0 // Not working
a%2 >> b ➞ if b is false ➞ 0 >> 0 ➞ 0
// For a%2 == 1
a%2 >> b ➞ if b is true ➞ 1 >> 1 ➞ 0
a%2 >> b ➞ if b is false ➞ 1 >> 0 ➞ 1
Thats means this is not working for notNotNot(6, true) is true but current solution gives false.
We can you ^(XOR) operator to make it correct Like (a,b) => !!(a%2 ^ b)
Now analysis the for (a,b) => !!(a%2 ^ b)
a%2 == 0 ➞ even number
a%2 == 1 ➞ odd number
// For a%2 == 0
a%2 ^ b ➞ if b is true ➞ 0 ^ 1 ➞ 1 // Now working
a%2 ^ b ➞ if b is false ➞ 0 ^ 0 ➞ 0
// For a%2 == 1
a%2 ^ b ➞ if b is true ➞ 1 ^ 1 ➞ 0
a%2 ^ b ➞ if b is false ➞ 1 ^ 0 ➞ 1
!(a%2 ^ b) use `!` to make int as boolean but solution result will reversed then
!!(a%2 ^ b) use `!` again to reversed it again and make it correct.
Example:
notNotNot = (a,b) => !!(a%2 ^ b);
console.log("!!!!true = ", notNotNot(4, true))
console.log("!!!!false = ", notNotNot(4, false))
console.log("!!!true =", notNotNot(3, true))
console.log("!!!false = ", notNotNot(3, false))

Write Shortage of if-else statement with two cases in one line

There is a javascript expression that assigns name variable to renamed variable.
It is always the same with one exclusion:
renamed = name == 'John' ? 'Johnny' : name;
However, I want two exclusions:
rename John to Johny
rename Alex to Alexander
All other names are assigned with no changes.
Is it possible to write this expression in one string?
renamed = (name == 'John' || name == 'Alex') ? <____> : name;
I need it to be done in one string.
Thank you.
(name === 'John' && 'Johny') || (name === 'Alex' && 'Alexander') || name;
If name is John, then it goes to the next part in the && expression and returns Johny.
If name is Alex, then the like in the first case returns Alexander.
If neither of them is true, then return the name as it is.
Demo
This solution works because, in JavaScript, && operator evaluates the expression in the left and if it is falsy then the value will be returned and the right hand side expression will not be evaluated at all.
If the expression in the left evaluates to be Truthy, then the expression on the right side will be evaluated and the result will be returned as it is. For example
console.log(1 && 2);
# 2
console.log(0 && 2);
# 0
It first evaluates 1, it is Truthy so it 2 is evaluated and the value is returned. That is why it prints 2.
In the second case, 0 is evaluated to be Falsy. So, it is returned immediately. That is why it prints 0.
The same way
console.log("John" && "Johny");
# Johny
John will be evaluated to be Truthy and so Johny will also be evaluated and returned. That is why we get Johny.
As per ECMA 5.1 Standard, Truthiness of an object will be decided, as per the following table
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
Note: The last line, Object, which includes both objects and Arrays.
renamed = (name == 'john') ? 'johney': (name == 'alex'? 'alexander' : name);
you can try this:
renamed = (name == 'John' ? 'Johnny' : (name == 'Alex' ? 'Alexander' : name));

JavaScript if(x) vs if(x==true)

In JavaScript , in which cases the following statements won't be logically equal ?
if(x){}
and
if(x==true){}
Thanks
They are not at all equal.
if (x)
checks if x is Truthy where as the later checks if the Boolean value of x is true.
For example,
var x = {};
if (x) {
console.log("Truthy");
}
if (x == true) {
console.log("Equal to true");
}
Not only an object, any string (except an empty string), any number (except 0 (because 0 is Falsy) and 1) will be considered as Truthy, but they will not be equal to true.
As per ECMA 5.1 Standards, in if (x), Truthiness of x will be decided, as per the following table
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
Note: The last line object, which includes both objects and Arrays.
But in the later case, as per The Abstract Equality Comparison Algorithm,
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
value of x will be converted to a number and that number will be checked against true.
Note:
In JavaScript, true is 1 and false is 0.
console.log(1 == true);
# true
console.log(0 == false);
# true
Several cases evaluate to false in the first form, such as empty string, 0, undefined, null.
If you want to be a bit more semantic about it, try the bang bang in front of the expression:
if(!!x){...}
this will convert the expression result to a truthy representing the same semantically. This is closer to an analogue to the expression you describe (x == true)
Also be aware that == is value comparions with type coercion, eg "3" == 3, whereas === asserts equal typing too.
So they are not the same, but often logically represent the same test, thanks to the semantics of the language and the !! you can use

Smart math regular expression

I know there are smart ppl out there. At the moment, I want to use one single and the most elegant regular expression to separate numbers to achieve some really simple math calculation.
It needs support some fuzzy number guessing for example:
1+.2 should equiv to 1 + 0.2
.1-.2 should equiv to 0.1 - 0.2
-.2+-100.2 should equiv to -0.2 - 100.2
Here is a quick demo I made up for you to play around
http://jsfiddle.net/av57A/60/
Is that possible to achieve those logic in one elegant regular expression?
Thanks.
I got it. Nice practice in regex for me. Also thanks for showing me jsfiddle. Never seen anything like that b4.
reg1 : ^[\-\d{1,}|\-*\.*\d*+]{1,}
reg2 (g) : \.{2}
reg3 (g) : ^(([\-]{0,})(\d*\.*\d*)?)|([\+\-\*\/]{1,})|((\d*)+(\.*\d*)?)
---
2-1 : 2 | - | 1
.1+.2 : 0.1 | + | 0.2
.2+1 : 0.2 | + | 1
-1-1.3 : -1 | - | 1.3
2+1 : 2 | + | 1
-2+1 : -2 | + | 1
2+-1 : 2 | + | -1
1+1.1 : 1 | + | 1.1
2.1+1 : 2.1 | + | 1
-1.0-1.3 : -1 | - | 1.3
-1-.3 : -1 | - | 0.3

When should you use parentheses inside an if statement's condition?

I have a if condition like so:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( name == 'Stack' && lastname == 'Overflow' )
alert('Hi Stacker!');
});
So my alert is fired...
If I put my condition inside a brackets like this:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( (name == 'Stack') && (lastname == 'Overflow') ){
alert('Hi Stacker!');
}
});
My alert is also fired...
My question is: When and why I should use parentheses inside my if condition? Thank you!
There is no much difference in your example.
You can read that for reference
Operator Precedence (JavaScript)
You use it to force associations, in your example this won't change anything. But consider this case:
A and B or C
is a lot different from
A and (B or C)
Here you would be preventing the expression from being understood as (A and B) or C which is the natural way javascript and maths do things.
Because of operator precedence :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
you'd better read this if you want more details
But basically == (equality) weights more than && (logical-and) , so A == B is evaluated before C && D given
C <- A == B
and
D <- E == F
so adding parenthesis to C or D dont matter,in that specific situation.
Brackets can be used, if multiple conditions needs to be checked.
For ex: User is also a Stacker if full name is 'StackOverflow' then add another condition with 'Or' operator.
if(((name == 'Stack') && (lastname == 'Overflow')) || FullName =='StackOverflow')
As you can see, name and last name are placed inside one bracket meaning that it gives a result either true or false and then it does OR operation with FullName condition.
And having brackets around name, lastname and fullname fields are optional since it doesn't make any difference to the condition. But if you are checking other condition with FullName then group them into bracket.
Brackets are never required in such situations.
Of course, try to read first solution (without) and second solution (with). Second one it's clear, fast-readable and easy to mantain.
Of course if you have to change precedence (in this case you just have an AND condition, but what if you need and AND and an OR? 1 and 2 or 3 priority changes between "(1 and 2) or 3" - "1 and (2 or 3)"
Brackets () are used to group statements.
Ex - if you have an expression '2 + 3 * 5'.
There are two ways of reading this: (2+3)*5 or 2+(3*5).
To get the correct o/p based on operator precedence, you have to group the correct expression like * has higher precedence over +, so the correct one will be 2+(3*5).
first bracket requires for complex condition to ensure operator precedence correctly. lets say a example
var x=1,y=1,z=0;
if(x==0 && y==1 || z==0)
{
//always true for any value of x
}
what will happen here
(0 && 1 ||1) ----> (0 ||1)----->1
&& has high precedence over ||
if(x==0 && (y==1 || z==0)) alert('1');
{
//correct way
}
if you do not use (y==1 || z==0) bracket the condition always will be true for any value of x.
but if you use (..) the condition return correct result.
Conditional statements can be grouped together using parenthesis. And is not only limited to if statements. You can run the example below in your Chrome Developer Tools.
Example 1:
Console Execution
false && false || true
// true
flow
false && false || true
| | |
|________| |
| |
| |
false or true
| |
|_________________|
|
|
true
Example 2:
Console Execution
false && (false || true)
// false
flow
false && (false || true)
| |
|______________|
|
|
false
Helpful resources for playing around with JSInterpreter and AST's:
https://neil.fraser.name/software/JS-Interpreter/
https://esprima.org/demo/parse.html#
Consider the statement
if( i==10 || j == 11 && k == 12 || l == 13)
what you would want is if either i is 10 or j is 11 And either k is 12 or l is 13 then the result shouldbe true, but say if i is 10, j is 11, k is 10 and l is 13 the condition will fail, because the fate of equation is decided at k as aoon as && comes in picture. Now if you dont want this to happen the put it like this
if( (i==10 || j == 11) && (k == 12 || l == 13))
In this ORs will be executed first and the result will be true.

Categories