90

I have some JavaScript code:

<script type="text/javascript">
$(document).ready(function(){
  $('#calcular').click(function() {
    var altura2 = ((($('#ddl_altura').attr("value"))/100)^2);
    var peso = $('#ddl_peso').attr("value");
    var resultado = Math.round(parseFloat(peso / altura2)*100)/100;
    if (resultado > 0) {
      $('#resultado').html(resultado);
      $('#imc').show();
    };
  });
});
</script>

What does the ^ (caret) symbol mean in JavaScript?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Torres
  • 5,330
  • 4
  • 26
  • 26

5 Answers5

101

The ^ operator is the bitwise XOR operator. To square a value, use Math.pow:

var altura2 = Math.pow($('#ddl_altura').attr("value")/100, 2);
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 6
    in a language like Javascript where types are so loose they barely exist, i'm almost surprised there are even bitwise operations :) – tenfour Sep 01 '10 at 13:15
  • 1
    I know the pow function (the Loreal Web Master seems no...) but I couldn´t find the ^ operator for javascript. Thanks for the link! – Torres Sep 01 '10 at 13:22
  • 3
    Nice catch! Forwarded it to my spanish friend, who got a little shocked. Noticed how for example 200cm/70kg gives you a BMI of infinity ;-) – Michael Sep 01 '10 at 14:29
  • Haha, that´s the same test I did!! now I know the answer, I feel better. I was scared for having a BMI of infinity... – Torres Sep 01 '10 at 16:16
  • 5
    To square a value, multiply it by itself. It's faster and more accurate on almost all platforms. – Stephen Canon Sep 01 '10 at 18:57
  • 8
    Gets much easier in ES7 : `2**5 //32` – Vinay Nov 09 '16 at 05:22
54

^ is performing exclusive OR (XOR), for instance

6 is 110 in binary, 3 is 011 in binary, and

6 ^ 3, meaning 110 XOR 011 gives 101 (5).

  110   since 0 ^ 0 => 0
  011         0 ^ 1 => 1
  ---         1 ^ 0 => 1
  101         1 ^ 1 => 0

Math.pow(x,2) calculates but for square you better use x*x as Math.pow uses logarithms and you get more approximations errors. ( x² ~ exp(2.log(x)) )

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
6

Its called bitwise XOR. Let me explain it:

You have :

Decimal Binary   
0         0
1         01
2         10
3         11

Now we want 3^2= ? then we have 11^10=?

11
10
---
01
---

so 11^10=01 01 in Decimal is 1.

So we can say that 3^2=1;

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
5

This is the bitwise XOR operator.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1

The bitwise XOR operator is indicated by a caret ( ^ ) and, of course, works directly on the binary form of numbers. Bitwise XOR is different from bitwise OR in that it returns 1 only when exactly one bit has a value of 1.

Source: http://www.java-samples.com/showtutorial.php?tutorialid=820

Sarfraz
  • 377,238
  • 77
  • 533
  • 578