New course! Every coder should learn Generative AI!
Try a free lesson+ 2
Some disturbing signs I don't understand in programming
1. What does "&" mean in JavaScript and how can it be compared to "&&". 2. What does "!" mean in JavaScript and how does it affect a parameter? 3. What is the difference between "++a" and "a++" and how is it possible that in some occasions, their values could output different results? And finally, what does "+=" mean in JavaScript?
8 Answers
+ 8
& is bitwise and:
00001000 (8)
& 01011000 (58)
--------
= 00001000 (8)
&& is logical and:
true && true = true
true && false = false
! is negation:
!true = false
!false = true
++a: increment a first, then use its value
a++: use a's value first, then increment it
a += b is the same as a = a + b
+ 8
Bitwise and means that the binary representations of two numbers are compared bit by bit. If both are 1, the "sum" is 1, otherwise it is 0.
11010101
+
00101011
=
00000001
10111100
+
11010010
=
10010000
11110101
+
11111100
=
11110100
and so on... It's not something you'll need every day...
+ 5
Anna Well said indeed!
Mofey As indicated already, logical operators (&& and ||) simply evaluate whether or not one, both, or neither boolean values are true.
Bitwise operators require an understanding of binary numbers and binary arithmetic.
A bitwise AND (&) will result in a new binary value where the bits are set if the corresponding bits of both operands are set to 1.
Example #1:
- Binary: 0101 & 1101 is 0101
- Integer: 5 & 13 is 5 which is truthy.
Example #2:
- Binary: 1001 & 0110 is 0000
- Integer: 9 & 6 is 0 which is falsey.
A bitwise OR (|) will result in a new binary value where the bits are set if either of the corresponding bits from the operands are set to 1.
Example #1:
- Binary: 0101 | 1100 is 1101
- Integer: 5 | 12 is 13 which is truthy.
Example #2:
- Binary: 1001 | 0110 is 1111
- Integer: 9 | 6 is 15 which is truthy.
Example #3:
- Binary: 1001 | 0000 is 0000
- Integer: 9 | 0 is 0 which is falsey.
+ 3
Mofey You may be referring to the Conditional Ternary Operator which would follow a format like this:
let x = bool_expr ? a : b;
This is shorthand for the if/else statement:
let x;
if(bool_expr) {
x = a; //assignment when true
} else {
x = b; //assignment when false
}
+ 2
Wow, your answer is excellent. I now understand better but Anna I still don't seem to get the "&". Please give me more info on that
+ 1
Just one more sign I don't seem to understand in JavaScript ("?"). Please Anna and David Carroll help me with a definition for that sign in JavaScript, what it is called and its function.
+ 1
Exactly, something like that Sir. So David Carroll, does that mean the operator is only an alternative for the if/else statement?
+ 1
Yep. It's common in several languages.