Passing a local variable from one function to another

I am new to JavaScript and wanted to ask the following: I have two simple functions, and I was wondering if there is a way to pass the value of a variable from one function to another. I know that I can just move it outside the function that will be used in other functions, but I just need to know how I can have one local variable and manipulate it in the second function. Is this possible and how?

Here is the code:

window.onload = function show(){ var x = 3; } function trig(){ alert(x); } trig(); 

The question is: how do I access the variable x (declared in the show function) from my second trig function?

+6
source share
3 answers

The first way is

 function function1() { var variable1=12; function2(variable1); } function function2(val) { var variableOfFunction1 = val; } 

The second way is

 var globalVariable; function function1() { globalVariable=12; function2(); } function function2() { var local = globalVariable; } 
+29
source

Adding to @ pranay-rana's list:

The third way:

 function passFromValue(){ var x = 15; return x; } function passToValue() { var y = passFromValue(); console.log(y);//15 } passToValue(); 
0
source

You can easily use this to reuse the value of a variable in another function.

// Use this in the source window.var1 = oEvent.getSource (). getBindingContext ();

// Get the value of var1 at the destination var var2 = window.var1;

-1
source

Source: https://habr.com/ru/post/915646/


All Articles