3

I am learning Javascript, and I am trying to go over everything I have learned so far. I am trying to figure out how to get a message back like an alert box when using the return statement. alert(Example(2,3)); works, also making a gobal variable like this works. var sum = Example(2,3); alert(sum);. But I bet there are better ways then I can think of.

function Example(x, y) {

    if (x * y === 108) {

        return true;

    } else {

        return false;

    }

}
Example(2, 3);
3
  • 1
    Either of those options work fine for an alert box. Commented Jul 25, 2012 at 22:16
  • Either would work, but it seems silly to call the variable sum when its value is either true or false. Commented Jul 25, 2012 at 22:31
  • By convention, function names starting with a capital letter are reserved for constructors, so the function name should be example. Commented Jul 25, 2012 at 22:42

2 Answers 2

7

Your function can be a lot simpler. Just return the boolean you get from the comparison:

function example(x, y) {
    return (x * y === 108);
}

As for how to make the alert box, I'd recommend not using alert boxes at all.

  • If you want to show something to the user, use plain HTML, jQuery or similar.
  • If you want to debug, use console.log or similar.

Alerts are highly annoying and prevent interaction with the page.

If for some reason you have to use an alert (for example, you're forced to debug on a system with no developer tools) then this will work just fine:

alert(example(2,3));
Sign up to request clarification or add additional context in comments.

4 Comments

about you said about alert, I dont agree with you. Alerts are the only way which you said in your post to stop the script and give you an information. There may be other implementation to stop the script and give an information but it's the most useable way. Hope me right.
"Alerts are the only way ... to stop the script" If you want to stop the script at a specific place you can set a breakpoint.
Not useable everytime, everywhere. You may do not have dev-tool :)
@EnesUnal: OK, thanks for pointing that out. Updated answer. Please let me know if you still think it can be improved.
6

Have it this way, :)

function Example(x, y) {
    return x * y === 108; 
}
Example(2, 3);

3 Comments

yea but the above code you gave me doesn't give any feedback in a browser. How would I use this code and give me a feedback of true or false. I've seen many people say not to use console.log, same with document.write and now alert.
@Sam: If you want to debug something, use console.log, set breakpoints, etc.
@Felix Kling breakpoints are for debugging? I have firebug but I am not really sure how to use it yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.