Home > Software engineering >  Problem with math operations in javascript [closed]
Problem with math operations in javascript [closed]

Time:10-04

I have a question regarding the code:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var a = 3;
var x = 275.15 * a;
var z = 298.15 * a;
document.getElementById("demo").innerHTML = x, z;
</script>

</body>
</html>

I want to return both x and z, but it seems like this code only returns x. What am I doing wrong? :)

CodePudding user response:

You're using the comma operator here: .innerHTML = x, z;. The comma operator works like this: It evaluates its left-hand operand, throws away the result, then evaluates its right-hand operand and takes that value as its result. So what you have there is equivalent to .innerHTML = z (since x has no side effects). If you want to show both, use string concatenation (.innerHTML = String(x) ", " z;), or a template literal (.innerHTML = `${x}, ${z}`;), or similar.

CodePudding user response:

<p id="demo"></p>

<script>
  var a = 3;
  var x = 2 * a;
  var z = 9 * a;
  document.getElementById("demo").innerHTML = (x  ","  z);
</script>

it's not a problem with math operators,hope this will help u

  • Related