What does this JavaScript code mean?
flag &= ~CONST
Is it append, prepend, intersection or something else?
What does this JavaScript code mean?
flag &= ~CONST
Is it append, prepend, intersection or something else?
Look at Bitwise operators.
&
puts 1 where both operands' bits are 1.
10000001 & 00000001 = 00000001
~
inverts the bits.
~10000000 = 011111111;
flag &= ~CONST
is short hand for flag = flag & ~CONST;
.
You may have seen something similar, e.g. number *= 10
.
This will turn off whatever constant represents.
For example, lets look at a hypothetical example of code which would represent the state of a window:
WS_HASBORDER = 0x01;
WS_HASCLOSEBUTTON = 0x02;
WS_HASMINIMIZEBUTTON = 0x04;
WS_HASMAXIMIZEBUTTON = 0x08;
WS_ISMAXIMIZED = 0x10;
We could represent the "state" of the window by using
windowState = WS_HASBORDER | WS_HASCLOSEBUTTON | ... etc
now, lets say we want to "turn off" one of these states, well, thats what your example code does...
windowState &= ~WS_HASBORDER
Now what the above code does, is it gets the compliment [i guess you could call it the inverted bits] of whatever is to its right, WS_HASBORDER.
So.. WS_HASBORDER has one bit turned on, and everything else is turned off. Its compliment has all bits turned on, except for the one bit that was turned off before.
Since I've represented the many constants as bytes, i'll just show you an example [not that javascript doesn't represent numbers as bytes, nor can you do so]
WS_HASBORDER = 0x01; //0000 0001
WS_HASCLOSEBUTTON = 0x02; //0000 0010
WS_HASMINIMIZEBUTTON = 0x04; //0000 0100
WS_HASMAXIMIZEBUTTON = 0x08; //0000 1000
WS_ISMAXIMIZED = 0x10; //0001 0000
_ now for an example
windowState = WS_HASBORDER | WS_HASCLOSEBUTTON | WS_HASMINIMIZEBUTTON |
WS_HASMAXIMIZEBUTTON | WS_ISMAXIMIZED;
0000 0001
0000 0010
0000 0100
0000 1000
and) 0001 0000
--------------
0001 1111 = 0x1F
So... windowState gets the value 0x1F
windowState &= ~ WS_HASMAXIMIZEBUTTON
WS_HASMAXIMIZEBUTTON: 0000 1000
~WS_HASMAXIMIZEBUTTON: 1111 0111
..To finish our calculation
windowState
&) ~WS_HASMAXIMIZEBUTTON
becomes
0001 1111
&) 1111 0111
-------------
0001 0111 = 0x07
Here are your resulting flags:
On:
WS_HASBORDER
WS_HASCLOSEBUTTON
WS_HASMINIMIZEBUTTON
WS_ISMAXIMIZED
Off:
WS_HASMAXIMIZEBUTTON
Hope that helps. Back to procrastinating homework I go! haha.