Home > Software engineering >  Observing unexpected Output : Javascript
Observing unexpected Output : Javascript

Time:08-01

a = Number(prompt());
b = Number(prompt());
if (a == b) {
  document.write("a==b")
} else if (a > b) {
  document.write("a>b")
} else {
  document.write("a<b")
}

using this script Input : a = 10, b = 20 Output : a

I am expecting a<b as a output, Please help, if I am doing any mistake.

CodePudding user response:

<b is interpreted as the start of a <b> tag. Your (malformed HTML) code results in the browser rendering:

a
<b <="" body="">
</b>

Don't use document.write - and if you do have to use it, keep in mind that you're writing HTML markup, not plain text.

Append an element or text node to the document instead.

const append = (text) => document.body.appendChild(document.createElement('span')).textContent = text;

a = Number(prompt());
b = Number(prompt());
if (a == b) {
  append("a==b")
} else if (a > b) {
  append("a>b")
} else {
  append("a<b")
}

CodePudding user response:

You are having "<" in your result which will be treated as a element opening. So you need to use &lt for "<" and &gt for ">".

a = Number(prompt());
b = Number(prompt());
if (a == b) {
  document.write("a==b")
} else if (a > b) {
  document.write("a&gt;b")
} else {
  document.write("a&lt;b")
}

  • Related