0

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

4
Contributors
4
Replies
24
Views
7 Years
Discussion Span
Last Post by jaycastr
0

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!

Edited by Chokladkakan: Typos.

0
<!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.

Edited by rajarajan07: n/a

0

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?";
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.