Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a local variable from one function to another

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?

like image 202
user1393266 Avatar asked May 14 '12 08:05

user1393266


People also ask

How do you pass a local variable to another function?

Here is some code: window. onload = function show(){ var x = 3; } function trig(){ alert(x); } trig();

Can I access a local variable in another function?

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.

How do you pass data from one function to another in python?

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.


2 Answers

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; } 
like image 122
Pranay Rana Avatar answered Sep 26 '22 04:09

Pranay Rana


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(); 
like image 23
Asim Mahar Avatar answered Sep 26 '22 04:09

Asim Mahar