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

Cipriano Mauricio
Cipriano Mauricio
3,560 Points

What am I doing wrong?

I can;t get through this step.

I'm calling the function:

getYear();

I'm creating a new variable (yearToday) and moving the returned value (year) from function into this new variable.

It's also saying that "Task 1 is no longer passing". I have not touched that code since Task 1.

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

getYear(); var yearToday = year;

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

getYear();
var yearToday = year;
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>

3 Answers

Tiffany McAllister
Tiffany McAllister
25,806 Points
var yearToday = getYear();

This will store the returned value of the getYear() function inside the yearToday variable.

Cipriano Mauricio
Cipriano Mauricio
3,560 Points

Got it. I thought you can access the variable year outside the function. Apparently I can't .

Thanks Tiffany!

Tiffany McAllister
Tiffany McAllister
25,806 Points

You're welcome! Yep, any variable that is declared inside a function can only be used within that function :)

Cipriano Mauricio
Cipriano Mauricio
3,560 Points

He goes over variable scope in a later video that explains this. Thx!

jobbol
seal-mask
.a{fill-rule:evenodd;}techdegree
jobbol
Full Stack JavaScript Techdegree Student 17,885 Points

Year is inside your function, you can't access it from the outside. The function itself returns the year, so all you have to do is set your variable equal to the call.

var yearToday = getYear();
Cipriano Mauricio
Cipriano Mauricio
3,560 Points

Got it. I thought you can access the variable year outside the function. Apparently I can't .

Thanks Josh!