0

I'm trying to make a web app, obviously for this I would need to know how to modify variables. I'm new to JS, is there something I'm missing? The following returns NaN

        var example = 30
    function add() {
        var example = example + 10
        document.getElementById("text").innerHTML = example
    }

    <P id="text"></text>
<button onclick="add()">
1
  • You redeclared the variable example. p.s. there's no such thing called: </text> (typo?) Commented Mar 26, 2018 at 4:04

4 Answers 4

1

You shouldn't redeclare the example variable inside the function again if you want to use the value assigned outside

 var example = 30
function add() {
    example = example + 10
    document.getElementById("text").innerHTML = example
}
<P id="text"></p>
<button onclick="add()">Add</button>

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

Comments

0

You can't re-declared the same variable example, And you have to complete properly close the button tag and paragraph tag

You will need these changes

var example = 30
function add() 
{
  example = example + 10
  document.getElementById("text").innerHTML = example
}
<p id="text"></p>
<button onclick="add()">submit</button>

1 Comment

Did you see any of the answer's in SO which starts with like "Hello, Joshua Riefman" and ends with "This would work 100 %"?
0

You are redeclaring the variable in the function - also you can abbreviate is as follows: example += 10; which is he quvalent of saying example is the value of example plus 10.

var example = 30
    
    function add() {
        example += 10;
        document.getElementById("text").innerHTML = example
    }
<button onclick="add()">Click Me</button>
<p id="text"></p>

Comments

0

You have re-declared the same variable, that's why on a function-scope view, example is NaN.

var example = 30
 function add() {
    example += 10;
    document.getElementById("text").innerHTML = example
 }

Comments

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.