I am a beginner in JavaScript and wanted to ask the following: I have two simple functions and was wondering if there is any way to pass a variable value from one function to another. I know I can just move it outside the function to be used in other functions as well but just need to know the way how I can have one local variable and manipulate with it in my second function. Is this possible and how?
Here is some code:
window.onload = function show(){
var x = 3;
}
function trig(){
alert(x);
}
trig();
The question is: how do I access variable x
(declared in the function show
) from my second function trig
?
Here is some code: window. onload = function show(){ var x = 3; } function trig(){ alert(x); } trig();
You can pass a local variable to a function CALLED by the function containing the local variable. You can return the value os a local variable to the function that CALLED the function containing the local variable. You can make a variable GLOBAL by declaring it outside of the functions.
You can return two things at once from any function, but you can only use one return statement. by using return x, y this returns a tuple (x, y) , which you can use in your main function.
First way is
function function1() { var variable1=12; function2(variable1); } function function2(val) { var variableOfFunction1 = val;
// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }
Second way is
var globalVariable; function function1() { globalVariable=12; function2(); } function function2() { var local = globalVariable; }
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With