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.
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.
Share Improve this question edited Dec 19, 2013 at 18:09 nsane asked Dec 19, 2013 at 17:55 nsanensane 1,7755 gold badges22 silver badges31 bronze badges 1-
2
Do you want to output
true
orfalse
? – VisioN Commented Dec 19, 2013 at 17:56
3 Answers
Reset to default 6Put 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
.
This evaluates to a string:
(x==y).toString();
So you can use:
"<p>The result is " + (x==y).toString() + "</p>"
var x=1;
var y=2;
document.write("<p>The result is "+(x==y)+"</p>");
Will do
The result is false