How to call a variable from one function to other function

2701 views javascript
3

I have two function outer is function first() and inner is second(),but when I call second function and calling the value of first function value its showing second function is undefined.How to call alert here any one can help me.Actually my requirement is like that,here is the code

html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div onclick=second() id="second">Click</div>

script

function first(){
    var x =1 ;  
function second(){
alert(x);
}
}

answered question

1 Answer

4

The inner function is defined in the first function scope. If you want to call it, you should not use it as an inner function. Define x as a global variable, call first or second whenever you like.

var x = 1;
function first(){
  x = 2;  
}

function second(){
  alert(x);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div onclick="second()" id="second">Click</div>

posted this

Have an answer?

JD

Please login first before posting an answer.