1

Below is my code, why does the value of y change?
what does var y = x | 5; mean?

code

 var x = 0;
      for(x; x < 11 ; x++)
    {
    var y = x | 5;
    console.log("\nx: "+x+ "  y : "+y)
    }

The result is

    x: 0  y : 5
    x: 1  y : 5
    x: 2  y : 7
    x: 3  y : 7
    x: 4  y : 5
    x: 5  y : 5
    x: 6  y : 7
    x: 7  y : 7
    x: 8  y : 13
    x: 9  y : 13
    x: 10  y : 15

why the value of y changes based on x.
On what basics y is calculated?

VenomVendor
  • 15,064
  • 13
  • 65
  • 96

2 Answers2

4

| is a bitwise OR operator! It works by converting the operands to binary, and doing a OR operation on every bits!

5 in binary is: 101. Now, try doing converting the other operand, apply the operation, you will see how y is dependent on x

For example:

9    =   1001
5    =   0101
         ____
9|5  =   1101  == 13

Also, note that your for-loop contains a syntax error. Remove the last ; in the line and you are good to go.

for(; x < 11 ; x++) 

Also, you wouldn't need x in the first part since it's already declared and initialised

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
2

| is a bitwise OR operator .It is doing OR operation

This is a bitwise or. Since bitwise operations only make sense on integers, 0.5 is truncated.

0 | x is x, for any x. 

   0 1 1 0 = 6  
   1 0 1 0 = 10 
   1 1 1 0 = 14 

9 | 5 = 1101 (which is 13)

SEE HERE

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151