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
jason chan
31,009 PointsSomeone walk me through this?
What does it output?
(function() {
var a = b = 5;
})();
console.log(b);
// 5, but why?
2 Answers
jared eiseman
29,023 Pointsif you console.log(a) it is also 5. So basically what this statement is saying is this:
I would like to create a variable, 'a', as well as a variable 'b'. 'a' should be equal to 'b', and 'b' is equal to 5, therefore 'a' is also equal to 5. Since it is all in the same statement (no semi-colons separating) the browser is processing it all at the same time, and is smart enough to figure out that the value it's assigning to both variables is 5.
Another way to write this, that is more legible would be:
var b = 5;
var a = b;
The whole "var a = b = 5;" thing is a pretty poor way of writing this, for future reference. If for nothing other than readability, the example I gave above is a more conventional way of writing it. Another example would be:
var b = 5,
a = b;
Hope this is what you were looking for.
Craig Garner
25,732 PointsYou have put the anonymous function in the global scope and it is automatically executed.