FishZone
FishZone

Reputation: 13

How to define value of variable from one function to another?

Hello i have this function for example:

var dt = new Date(); 
var now = dt.valueOf(); 
function date1() { 
  var d1 = Math.ceil(
    (Math.abs(now - dt.setUTCFullYear(2005))) / (1000*3600*24*365)
  ); 
}

And i want to get value from d1 var to another function for example:

function res() { 
  document.write(d1).value; 
}

Upvotes: 1

Views: 24

Answers (2)

Robert
Robert

Reputation: 2669

If you want to access the local variables of function A from function B you have to put the definition of function B somewhere inside of the body of function A.

function A() {
  var variable;

  function B() {
    // can access variable here
  }
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Make your function return the value:

var dt = new Date(); 
var now = dt.valueOf(); 
function date1() { 
  return Math.ceil( // <=== Change, using return rather than setting a variable
    (Math.abs(now - dt.setUTCFullYear(2005))) / (1000*3600*24*365)
  ); 
}

Then call the function when you need the value:

function res() { 
  document.write(date1()).value; 
  // Change -----^^^^^^^
}

Side note: As far as I'm aware, document.write doesn't have any return value, so the .value on the end of your document.write line doesn't make any sense, and will probably result in a TypeError complaining that you're trying to access a property on undefined.

Side note 2: In general, document.write isn't a great way to put information on web pages, use the DOM instead. Like most rules, there are exceptions.

Upvotes: 1

Related Questions