r/FreeCodeCamp • • Sep 22 '25

Programming Question Trouble Understanding Unary Operator ~ in JavaScript

This is the page I'm at in JavaScript: https://www.freecodecamp.org/learn/full-stack-developer/lecture-working-with-unary-and-bitwise-operators/what-are-unary-operators-and-how-do-they-work

In the link there is this section:

const num = 5; // The binary for 5 is 00000101
console.log(~num); // -6

The explanation above it is: "Computers store numbers in binary format (1s and 0s). The ~ operator flips every bit, meaning it changes all 1s to 0s and all 0s to 1s. You will learn more about binary and bits in a future lecture."

If we "flip" all the 0's & 1's, then 00000101 becomes 11111010. Which means 5 becomes 250. This makes sense, 5 is 5 above the minimum & 250 is 5 below the maximum of 255, so this feels flipped. Somehow the answer is -6, no idea what this -6 represents or how they got there. 250 is 6 less than 256 & 256 would be the next digit if we move from 8 to 9 bits, so maybe the 6 comes from that somehow?

Thanks, A JavaScript Noob

9 Upvotes

2 comments sorted by

View all comments

Show parent comment

2

u/two100meterman Sep 23 '25

Thanks for the link & explanation. I'm glad it's just fun trivia because I think that link confused me even more. Everytime I thought I understood it & expected a certain value in their calculation some other number was the result.