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
Manolo Pina
6,342 PointsHow to change this variable ?
var n;
n= "variable";
jQuery(function(){
$(document).ready(function(){
n= "string";
});
});
console.log(n);
```
Manolo Pina
6,342 PointsI'm want to change the value of the variable in jquery function but show its value out of the function
6 Answers
Peter Hearne
6,803 Pointsvar variable = "variable" { }
Peter Hearne
6,803 Pointsi agree with Adam, its not very clear and my guess was based on you using the word " variable " as an example..
Adam Sackfield
Courses Plus Student 19,663 PointsMy take on it is that he is on the scope lessons. Will post an answer for now.
Peter Hearne
6,803 Pointsok if n = variable in your function it might be conflicting with the claim that n = "string" in your jquery? all i can do is offer an educated guess
Manolo Pina
6,342 PointsIf I declare the variable n inside the jquery function, could it work ?
Adam Sackfield
Courses Plus Student 19,663 PointsRight try this.
var name = "Adam"
$(.btn).click(function(){
name = "Manolo"
});
To change a Global Variable from within a function you can drop the keyword 'var' and just reference the name of the variable instead.
So my example will set a Global Variable to "Adam" then when the element with the class .btn is clicked it will change to "Manolo"
Peter Hearne
6,803 Pointswell im thinking n would have to = the same in both your function and jquery but maybe somebody else will know
Peter Hearne
6,803 Pointsi believe adam is right sorry i was getting mixed up
Adam Sackfield
Courses Plus Student 19,663 PointsAdam Sackfield
Courses Plus Student 19,663 PointsCould you be more clear on what you mean. Also using the word 'variable' for a var is probably not a best practise.