Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Returning a Value from a Function

Confused about how to store the returned value of the function in a new variable

So I'm at the step where you're supposed to call a function getYear(), return the result and store it in a new variable. How do I write this??

script.js
function getYear() {
 var year = new Date().getFullYear();
 return year;
}

getYear();
index.html
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JavaScript Basics</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

2 Answers

Gianmarco Mazzoran
Gianmarco Mazzoran
22,076 Points

Hi,

like for the variable inside the function, you need to create a new variable that it's value is the function itself. Like this:

function getYear() {
  var year = new Date().getFullYear();
  return year;
}

var yearToday = getYear();

So if in the future you need to call the function getYear(), you can simply type yearToday!

Thanks so much!

Steven Parker
Steven Parker
231,248 Points

You can declare a new variable and assign it in one step. Here's a generic example (not a spoiler):

var yourNewVariable = someFunction();

:point_right: Be aware that using the variable at a later point in the program is not the same thing as calling the function again. Depending on what the function does, the return value could be different at a later time, but the variable will still have the value returned by the function when the variable was created.

Sorry for the late response, but thanks so much for the help. Much appreciated!