Home > OS >  What is the purpose of this operator " =" in this context?
What is the purpose of this operator " =" in this context?

Time:11-16

I am learning some basic JS and how its results are viewed on HTML. I come across this:

<!DOCTYPE html>
<html>
<body>
    <h1>Demo: JavaScript Arithmatic Operators</h1>
    <p>x = 5, y = 10, z;</p>
    <p id="p1">x y=</p>
    <script>
        var x = 5, y = 10;
        var z = x   y
        document.getElementById("p1").innerHTML  = z; 
    </script>
</body>
</html>

As far as I have read on the operator ' =', it adds the right operand to the left operand and then saves it back to the left operand. However, I am confused on what is the purpose of ' =' in this line?

CodePudding user response:

document.getElementById("p1").innerHTML  = z; 

// equals to
document.getElementById("p1").innerHTML = document.getElementById("p1").innerHTML   z; 

// in this case
document.getElementById("p1").innerHTML = "x y="   15

// finally, you will see "x y=15" on the page

CodePudding user response:

if you have two variable do you want to add these two and store in one of them like

a=5; b=4;

a = a b this is same as a = b; so in your case you can use

document.getElementById("p1").innerHTML = document.getElementById("p1").innerHTML   z; 

or 
document.getElementById("p1").innerHTML  = z; 

CodePudding user response:

It simply appends right operand value(15) to content of <p id="p1"> tag(thats x y). So it results as "x y=15"

For more clarification:

document.getElementById("p1").innerHTML = z; In this line, it takes the innerHTML(current content) of html element with id 'p1'(here its a <p> tag), append right operand(here its variable z: which contains value 15 after js add operation result) to that content, and set it back as that <p> tag's innerHTML.

  • Related