Sam Satanas
Sam Satanas

Reputation: 79

Return true or Return false

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);

Upvotes: 3

Views: 5489

Answers (2)

Mark Byers
Mark Byers

Reputation: 837946

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));

Upvotes: 7

totten
totten

Reputation: 2817

Have it this way, :)

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

Upvotes: 6

Related Questions