Hello All,
I have a simple question

How do i get a variable from one function into another function. I am new to javascript.
Here is my code

function timestart(that) 
{
    var x =  new Date();
    that.value = x;
	
}
function timeend(that) 
{	
    var y = new Date()
    that.value = y;
}

function duration()
{
    var z = x - y;
    alert("duration=" + z)

}

Any insight is greatly appreciated. Thanks

Hello jaycastr,

A variable declared inside a JavaScript function will only be local if you write it like this:

function func(){
    var x = 5;
}

However, if you don't use the var keyword, it will be added onto the window element, and thus global:

function func(){
   x = 5;
}

Note: if a variable is referenced in JavaScript which isn't defined, it will do that for you, which is why this work.

Edit: I thought I might as well edit your example, to prevent confusion:

function timestart(that) 
{
    x =  new Date();
    that.value = x;
	
}
function timeend(that) 
{	
    y = new Date()
    that.value = y;
}

function duration()
{
    var z = x - y;
    alert("duration=" + z)

}

And, to clarify, what is really happening now is that the last function calls window.x and window.y!

Member Avatar for rajarajan2017
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script language="javaScript">
function Do_This() {     
   alert(7);  
   And_This(10);
}  
function And_This(num) {
   alert(num);
}
</script>
</head>

<body onLoad="Do_This();">
</body>
</html>

Instead of 10 you can pass the variable.

One of the things I haven't seen yet is that you can send a variable from a function you call back to function that you called from.

function func1 (){
 var msg = "Here I am";
 var newMsg = func2(msg); 
 alert(newMsg); /* will print out "Here I am And Now Where are You?" in an alert box */
}
function func2(msg){
  return msg + " And Now Where are You?";
}

Thanks Guys very appreciative of ur help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.