1

Suppose I want to incorporate a boolean value in some string I print out, like

var x=1;
var y=2;
document.write("<p>The result is "+x==y+"</p>");

Normally, this does not give me the requred output. Is there a method to directly print boolean expressions in the document.write() itself? I do not want to use if-else and then assign separate values to variables and then print them. PS - I have just started learning JavaScript.

1
  • 2
    Do you want to output true or false? Commented Dec 19, 2013 at 17:56

3 Answers 3

6

Put parentheses around the boolean expression:

document.write("<p>The result is " + (x == y) + "</p>");

If you don't, you're doing this:

document.write(("<p>The result is " + x) == (y + "</p>"));

And in general, don't use document.write.

Sign up to request clarification or add additional context in comments.

3 Comments

What do I use then? I'm relatively new to JavaScript and so far the tutorials at W3Schools have used document.write. Are there any loopholes with it?
@nisargshah95 First advice would be to avoid W3Schools unless you already know what you're doing. Second, if you're just learning JavaScript, use the console--you don't need to write any HTML.
@nisargshah95 The JavaScript console, available by default in Chrome, and maybe Firefox as well, if it isn't, install Firebug. Or use node.js.
3

This evaluates to a string:

(x==y).toString();

So you can use:

"<p>The result is " + (x==y).toString() + "</p>"

Comments

1
var x=1;
var y=2;
document.write("<p>The result is "+(x==y)+"</p>");

Will do

The result is false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.