Search code examples
javascriptpowsqrtreferenceerror

Square root with javascript returns ReferenceError


I'm trying to get the square root of a number using javascript.
To do that, I tried the following codes:

<script>
var rad = sqrt(4);
alert(rad);
</script>

(this returns in Firefox's console "ReferenceError: sqrt is not defined")

<script>
var rad = pow(4,0.5);
alert(rad);
</script>

(but I get "ReferenceError: pow is not defined")

What am I doing wrong?


Solution

  • Yes, that error is reasonable, since you're calling it as a separate function. Prefix them with Math. as those methods exist in Math object

    var rad = Math.sqrt(4);
    alert(rad);
    

    Another way is to create a separate function but I would not advise the use of this, but anyway, here it is

    function sqrt(n){
      return Math.sqrt(n);
    }
    var rad = sqrt(4);
    alert(rad);