</!DOCTYPE html>
</html>
</body>
<p>Given that y=5, calculate x=++y, and display the result.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var y=5;
var x=++y;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x + ", y=" + y;
}
</script>
<p><strong>Note:</strong> Both variables, x and y, are affected.</p>
</body>
</html>*/
Clearly, I’m a beginner but I have no one else to ask. It would be helpful if someone could explain the reason behind demop.innerHTML="x=" + x + ", y=" +y; in this code.
That line of code doesn’t increment anything, in that line the
+is a string concatenation operator, not a number addition operator. It’s used for building up a string (it doesn’t changexory), which is then assigned todemoP.innerHTML, which replaces the content of the DOM element with that string’s contents.The line that’s a bit harder to understand for a beginner is this one:
That does three things:
It declares a variable called
xin the current scope (var).It increments the value of
y.It assigns the incremented value to
x.So both
xandyend up with6, since the increment happens before the value ofyis used to initializex. This is called a “prefix increment”. “Pre” because it happens before we use the value for something.Like most languages that derive their main syntax from B (so, C, C++, Java, C#, JavaScript, and many others), there’s also a “postfix” increment:
“Post” because we increment after using the value. If the line were as above,
xwould get5(y‘s old value) andywould get6.