1

I assign document.getElementById("outcome").value to variable outcome. When I click the button, I want to set value of input that has id "outcome" to "Something".

But when I execute my code below, input form outcome was not set. Still, input form outcome is nothing happened.

function throwDice() {

    var point=document.getElementById("point").value;
    var outcome=document.getElementById("outcome").value;
    outcome=Somthing;
}

After that I modify my code right this.

function throwDice() {

    var point=document.getElementById("point").value;

    document.getElementById("outcome").value="Something";
}

All I do is that remove assigning variable outcome and assign "Something" to document.getElementById("outcome").value directly. In this case value of input form outcome is "Something".

My question is why outcome="Something" isn't operate.

1
  • Variables aren't references to properties. Commented Apr 9, 2017 at 23:06

1 Answer 1

2

Situation:

In your first code, you are only overwriting outcome variable value with "Something" instead of writing it into element with id outcome, so if you write:

Explanation:

Here you declared outcome variable and set its value to the value of your input:

var outcome=document.getElementById("outcome").value;

And here in this line you are resetting outcome variable to "Something"

outcome=Somthing;

So in this case outcome variable was just holding the input value, then you changed it to "Something".

So to answer your question: why outcome="Something" isn't operate?, it's because outcome doesn't refer the input element value, but only holds its value.

In other words:

So in your first code you were just doing something like this:

var outcome = 5;     //outcome here is 5
outcome = "Something";    //outcome is changed to "Something"

In JavaScript variables are loosly typed that's why you see this behaviour, you can take a look at Understanding Loose Typing in JavaScript for further reading.

Sign up to request clarification or add additional context in comments.

2 Comments

although my terrible English, You answer to my question. Thank you for your rapid answer. I understand my mistake.
@nuroococoa if it helps you can you please accept my answer. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.