0

I have a function in javascript that returns two values:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [day, dayW];
}

When I call this function (within another function) I whant only one of this values.

function print_anything() {
  console.log("Today is the " + today_date() + " of the month.");
}

I know it's a very basic and newbie question. But how do I do that?

craftApprentice
  • 2,697
  • 17
  • 58
  • 86

2 Answers2

8

Does that actually return 2 values? That's a new one to me. Anyhow, why not do this?

return {'day': day, 'dayW': dayW };

and then:

console.log("Today is the " + today_date().day + " of the month.");
Tim Mac
  • 1,149
  • 1
  • 8
  • 17
  • And it's as simple as that **+1** – iConnor Jul 27 '13 at 16:18
  • FWIW, the return statement doesn't return 2 values. It's just the comma operator; which returns the last value in the statement. TLDR, only the last statement is returned. – Matt Jul 27 '13 at 16:19
1

You can return them in an object literal

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return { "day" : day, "dayOfWeek" : dayW };
}

and access like this

function print_anything() {
  console.log("Today is the " + today_date().day + " of the month.");
}

or you can return the values in an array:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [ day, dayW ];
}

and then access the first one like this

function print_anything() {
  console.log("Today is the " + today_date()[0] + " of the month.");
}
go-oleg
  • 19,272
  • 3
  • 43
  • 44