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
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 PointsHow can I pass a variable outside of a function
I would like to use a the variable outside of a function. How do i accomplish this? I want the variable to be 7.
Code:
var myNum = 5;
function hello(myNum){
return myNum = 7;
}
alert(myNum);
2 Answers
Crisoforo Gaspar Hernández
18,302 PointsHi, you can reassign any value returned from a function to another variable or the same one, for example:
var a = 1;
function add_two( n ){
return n + 2;
}
// Then you can reasign the value after the function is executed like
a = add_two( a );
// a now has the value of 3.
console.log( a );
travis spade
9,816 PointsIf you want the hello function to run you need to call it. This simplest way to do this would be to assign the global variable in the hello function. Since myNum is in the global scope you wouldn't need to return anything. I don't think this is a good way to do this, but here is what it would look like:
var myNum = 5;
function hello(someNum){
myNum = 7;
}
// call the function
hello();
alert(myNum);
I think a better way to do this would be to pass the value to the function then assign the returned value to the variable like this:
var myNum = 5;
function hello(someNum){
someNum = 7;
return someNum;
}
myNum = hello(myNum);
alert(myNum);
Crisoforo Gaspar Hernández
18,302 PointsLooks like you have the correct syntax for markdown, but maybe you need to add some spaces like
before the: ```
Also you have the preview button on the right corner of the text area where you can see the live preview of your current comment.
As a reference you can use the Github Markdown guide to see how to highlight the code: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code
travis spade
9,816 PointsCrisoforo, Thanks, adding a carriage return after the colon and before the three backticks fixed the issue.
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 PointsDennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 Pointsthank you very much.
travis spade
9,816 Pointstravis spade
9,816 PointsCrisoforo, I tried submitting an answer, but my code block didn't get converted like yours. As you can see in my answer below you can still see the three backticks. How can I get my code block to look pretty like yours? What am I missing?