Search code examples
javascriptreturnvscode-code-runner

Why I can't see an output in a text editor, even if I'm sure that the code is right?


I'm currently studying JavaScript using HeadFirst JS book. I understand everything until this moment. I put the code in a text editor in order to check the output. There weren't any errors in a console; thus, the code is right. But I still can't get the gist. I think that the problem is related to the return statement (how it works, etc), 'cause when I tried the console.log function I could see some result.

var x = 32;
var y = 44;
var radius = 5;
var centerX = 0;
var centerY = 0;
var width = 600;
var height = 400;

function setup(width, height) {
centerX = width/2;
centerY = height/2;
}

function computeDistance(x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
var d2 = (dx * dx) + (dy * dy);
var d = Math.sqrt(d2);
return d;
}

function circleArea(r) {
var area = Math.PI * r * r;
return area;
}

setup(width, height);
var area = circleArea(radius);
var distance = computeDistance(x, y, centerX, centerY);
alert("Area: " + area);
alert("Distance: " + distance);

Solution

  • Are you trying to run this with Node? You cannot alert values with Node in a terminal. Instead, you can use console.log() to print the output on the console.

    However, if you're running this in a browser, encapsulate it as an html page.

    <html>
    <script>
    
    // Your code here //
    
    var area = circleArea(radius);
    var distance = computeDistance(x, y, centerX, centerY);
    alert("Area: " + area);
    alert("Distance: " + distance);
    
    </script>
    </html>