-1

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);
}
}
carreankush
  • 621
  • 2
  • 9
  • 32

5 Answers5

0

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>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75
0

Define x as a global variable.

How to do it- Define variable outside of the functions and it will be accessible to all function's scope.

Parth Lukhi
  • 181
  • 8
0

the nested functions are local and you cannot call from the outside scope.

<button onclick=first() id="second">Click</button>


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

}
ijhar
  • 11
  • 4
0

You need to define the variable as Global here is an example how to use global variables in your Javascript codes

function m(){  
window.value=100;//declaring global variable by window object  
}  
function n(){  
alert(window.value);//accessing global variable from other function  
}  

Therefore, you can edit your code like this :

function first(){
    window.value =1 ;  
function second(){
alert(window.value);
}
}
Ashouri
  • 906
  • 4
  • 19
0

There are actually multiple ways to achieve that. As mentioned before, you can put your variable to a global scope.

But it's a very nice example of so-called module pattern. You can access your nested function by returning it by the wrapping one:

function first() {
  var x = 1;

  function second() {
    alert(x);
  }
  return second(x)
}

alert(first());

This pattern is very useful, because it allows you to create so-called private variables, which are accesible only by calling a certain method.

HynekS
  • 2,738
  • 1
  • 19
  • 34