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 trialiwgpnjvycw
8,577 PointsConfused 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??
function getYear() {
var year = new Date().getFullYear();
return year;
}
getYear();
<!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
22,076 PointsHi,
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
!
Steven Parker
231,248 PointsYou can declare a new variable and assign it in one step. Here's a generic example (not a spoiler):
var yourNewVariable = someFunction();
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.
iwgpnjvycw
8,577 PointsSorry for the late response, but thanks so much for the help. Much appreciated!
iwgpnjvycw
8,577 Pointsiwgpnjvycw
8,577 PointsThanks so much!