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
behar
10,800 PointsJavascript, switching variables
Quick question about switching variables in Javascript. In python we can do the following:
test1, test2 = test2, test1
That will switch test1 for test2 and test 2 for test 1, in a single line of code. This approach dosent work in javascript tho, is there a similiar way to do it?
1 Answer
Steven Parker
243,658 PointsYes you can do this in JavaScript also, but the syntax is slightly different:
[test1, test2] = [test2, test1];
As you see, the terms are wrapped in array literals on both sides. This is known as "destructuring assignment".
behar
10,800 Pointsbehar
10,800 PointsTy as always steven!
Kieran Barker
15,028 PointsKieran Barker
15,028 PointsHow long have you been programming, Steven? :-)
Steven Parker
243,658 PointsSteven Parker
243,658 PointsAbout 8 for JavaScript. Around 35 in general.