2

I was writing some calculations involving exponents in Javascript and due to my habit of using carets in Microsoft Excel, I typed x^2 in the code. It still gave me an answer but it wasn't what I wanted. What does ^ do in javascript?

alert(Math.pow(3,2)); //result is 9
alert(3^2);           //result is 1
blank_kuma
  • 335
  • 6
  • 16

2 Answers2

3

That is a bitwise XOR. Use Math.pow for exponents.

If you do 3^2 you are actually doing:

3 XOR 2

Computers use Binary so they see

11 XOR 10

Put that into a table:

11     1 ^ 0 = 1
10     1 ^ 1 = 0
--
01

In simple terms:

XOR will take the two numbers in binary, and for the bit to be true, they must be different

Here's a list of all operators like ^


Math.pow() takes a base and an exponent:

Math.pow(3, 2) --> 32 --> 9

Math.pow(5, 6) --> 56 --> 15,625

Math.pow(7, 3) --> 73 --> 343

Community
  • 1
  • 1
Downgoat
  • 13,771
  • 5
  • 46
  • 69
2

In x^2, ^ is the bitwise XOR operator and not the exponentiation operator as you expected, for that use: Math.pow(x, 2).

Dan D.
  • 73,243
  • 15
  • 104
  • 123