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
Alexandra Wakefield
1,866 PointsIs there a way to use a variable that is inside a function?
Yesterday I saw someone use 'function' and I've tried to replicate it's use in the Doing Math part of JavaScript Basics. However, I noticed while trying to use variable 'yearsAlive' in 'console.log' that it wouldn't work. Is there something I could do in order to use 'yearsAlive' outside of the function?
Here's the code:
var time = [
secondsPerMin = 60,
minsPerHour = 60,
hoursPerDay = 24,
daysPerWeek = 7,
weeksPerYear = 52
];
var secondsPerDay = time[0] * time[1] * time[2];
function secondsAlive() {
var yearsAlive = prompt("How old are you?");
var secondsPerYear = time[0] * time[1] * time[2] * time[3] * time[4];
var message = yearsAlive * secondsPerYear;
return message;
}
document.write(
"There are " + secondsPerDay + " seconds in a day."
+ "<br/><br/>" +
"You have been on this Earth for about " + secondsAlive() + " seconds."
);
1 Answer
Ted Dunn
43,783 PointsOne way would be to declare the variable yearsAlive outside of the function. This would give the variable "global" scope which means it could be accessed throughout the program.
var yearsAlive;
function secondsAlive() {
yearsAlive = prompt("How old are you?");
(other statments in function)
}
Alexandra Wakefield
1,866 PointsAlexandra Wakefield
1,866 PointsOh, that makes sense. Thank you, Ted!