</!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.
3 Answers 3
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 change x or y), which is then assigned to demoP.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:
var x=++y;
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 x and y end up with 6, since the increment happens before the value of y is used to initialize x. 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:
var x = y++;
"Post" because we increment after using the value. If the line were as above, x would get 5 (y's old value) and y would get 6.
1 Comment
demoP.innerHTML = "x = " + x + ", y = " + y;
This sets the HTML of the element identified by demoP. + will concatenate the strings and the numbers into one string which will be the HTML of demoP.
Comments
When you click the button "Try it" the function myFunction() is executed and the HTML inside the element with id demo is changed to: x=6, y=6
</!DOCTYPE html>, and your openinghtmlandbodytags should not have a forward slash. There is an extraneous*/at the end of the document as well?