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.
asked Dec 19, 2013 at 17:55
nsane
1,8155 gold badges24 silver badges31 bronze badges
3 Answers 3
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.
answered Dec 19, 2013 at 17:58
Dave Newton
161k27 gold badges264 silver badges311 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
nsane
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?
Dave Newton
@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.
Dave Newton
@nisargshah95 The JavaScript console, available by default in Chrome, and maybe Firefox as well, if it isn't, install Firebug. Or use node.js.
This evaluates to a string:
(x==y).toString();
So you can use:
"<p>The result is " + (x==y).toString() + "</p>"
answered Dec 19, 2013 at 17:58
DontVoteMeDown
21.5k10 gold badges72 silver badges113 bronze badges
Comments
var x=1;
var y=2;
document.write("<p>The result is "+(x==y)+"</p>");
Will do
The result is false
answered Dec 19, 2013 at 17:59
Victor Häggqvist
4,4853 gold badges29 silver badges35 bronze badges
Comments
lang-js
trueorfalse?